Chapter - 3, Object Oriented Programming in C++, HSSC-II (12th Class) Computer Science Key Point Notes

Chapter - 3, Object Oriented Programming in C++, HSSC-II (12th Class) Computer Science Key Point Notes

12th Class (HSSC-II) Computer SLO Based Key Point Notes

(National Book Foundation - As Federal Textbook Board, Islamabad 
Based on National Curriculum Pakistan 2023-2024 and Onward prescribed by Federal Board of Intermediate and Secondary Education, Islamabad, and All Pakistan Boards) 

{Contact WhatsApp 03339719149 for Class-XII Computer Science Complete SLO-Based Key Points notes in pdf format as well as in PowerPoint Presentation for preparing/delivering the Lectures}

************************************

👉👉👉 Computer Science 12th Class Notes (Main Page)

************************************

Unit 3: Object-Oriented Programming in C++


3.1 Introduction

• Object Oriented Programming (OOP):

  • It refers to a programming method that is based on objects such as students, vehicles, buildings, etc.
  • It provides a set of rules for defining and managing objects.
  • An object can be considered a thing that has attributes and performs a set of activities.

Introduction to C++:

  • It was created by Bjarne Stroustrup in the early 1980s at Bell Laboratories.
  • C++ is a general-purpose language.
  • Its main purpose was to provide facilities to write powerful programs easily and quickly
  • It is commonly used for developing high commercial software, games, and graphics-related programs.


Instruction:

  • A statement that directs the computer to perform a task is called instruction.
  • The computer needs instructions from the users to do any task.

3.1.1 Computer Program/Software:

A set of well-defined instructions given to computers to perform a specific task is called a program or Software.

Programming Language:

  • A programming language is a tool for writing instructions for a computer. OR
  • Programming language is a set of rules, symbols, and special words used to develop a computer program.
  • The instructions of the program are written in a specific manner and according to the rules of the programming language.

Syntax:

The set of rules of a programming language for writing statements of the program is known as the syntax of the language.

3.1.2 Header File and Reserved Words

Header File

  • Header files are the collection of the standard library functions to perform different tasks.
  • There are many header files for different purposes which contain different types of predefined functions.
  • The extension of the header file is “.h”
  • The header file must be included in the program before using any of its functions in the program.
  • The name of the header file is written in angle brackets < > 

Reserved Words

  • In the C++ language, a reserved word is a word that has a predefined meaning and purpose which is defined by the developer of C++ language.
  • They are also known as keywords.
  • It cannot be changed or redefined by the user.
  • Keywords can only be used for the purpose for which it is defined.

List of keywords



3.1.3 Structure of C++ Program

The format or way according to which a computer program is written is called the structure of the program.
The basic structure of a C++ program consists of the following main parts:
  1. Preprocessor Directives
  2. The main() function
  3. Program Body (C statements)
Example


Preprocessor Directive

  • The instructions given to the C-compiler before the compilation process are called preprocessor Directive.
  • They are also known as Compiler Directive.
  • They are given at the beginning of the source code.
  • They are processed before compiling the source code by a program known as Preprocessor which is a part of a C-compiler.
  • Preprocessor Directive begins with a “#” sign.

Following are the important types of preprocessor Directive:
i.    Include directive
ii.   define directive

i. Include directive

The “include preprocessor directive” is used to include header files in the program.

The syntax of using “include directive is as follows 

                            #include < Header file name. h >

Many header files can be included in one program.

ii. Define directive

Define directive is used to define a constant.
It starts with the # symbol.

The syntax of the defined directive is as follows:

            #define identifier expression

Example:
            #define pi 3.14


main() function

  • The main() function is the place where the execution of a C program starts.
  • Every C program must have the main() function.
  • If a program does not contain the main() function, it can be compiled but cannot be executed.
  • The body of the main function is enclosed in curly braces { } which contain a statement.

The syntax of the main() function is as follows:

void main(void)
{
        body of the main function which contains statements;
}


3.1.4 C++ program statement Terminator:

  • A C++ statement is an instruction for the computer to do something.
  • The set of statements of the C program is written between curly braces.
  • Every C++ statement must be ended with a semicolon (;) which is known as a statement terminator.

3.1.5 Comment statement in C++ Program:

The comment statements are non-executable statements which are used to add remarks or comments in a program.

Comments are used:
  • To increase the readability of the program.
  • You can easily understand the logic of a program.
  • It can help in debugging and modifying the program.
In C program, comments can be added in a program in two ways:
  1. Single line comments: Comments on a single line are added by using the double slash “//”. For example:
  • A = L * W; // A formula to calculate the area of a rectangle.
  • int = a; // A statement to declare a variable of integer.
    2. Multi-line comments: Multi-line comments are inserted by placing /*
at the beginning of the comments and */ is placed at the end of the comments. For example:
  • /* A program to calculate the area of a rectangle */

3.2.1 Constants and Variables

Constant:

  • A constant is a quantity that cannot be changed during program execution.
  • It can be a number, a character, or a character string. A character string is a sequence of any number of characters.
  • Examples: 42, 7.25, ‘s’, “computer” etc.

Variable:

  • A quantity whose value may change during the execution of the program is called a variable.
  • A variable is a space in a computer’s memory, used to store data and given a name for easy reference. OR
  • In C language, a variable is a memory location that is identified by a name to store a data of particular type.

3.2.2 Rules for Naming a Variable:

Following are the rules for naming variables in C:
  1. A variable name may consist of digits, upper case, and lower case alphabets, and underscore symbols i.e. “_”
  2. The first character of a variable name must be an alphabet character or underscore.
  3. Keywords/Reserved words of C++ cannot be used as variable names.
  4. Special symbols such as $, @, %, #, etc. are not allowed.
  5. Two variables cannot be of the same name.
  6. C is a case-sensitive language. Variable names with the same spelling but different cases are treated as different variable names.
  7.  A meaningful name should be given to the variable which can help to understand the purpose of the variable.
  8. Blank space or comma is not allowed.

3.2.3  Different C++ data types for variable

Integer

  • It is a data type that is used to define numeric variables to store whole numbers, such as -3, 367, +2081, etc.
  • The short form of an integer is int.
  • The following table shows the integer types:


Floating Point

  • It is a data type that is used to define variables that can store numbers that have fractional parts such as 3.75, -2.1, 388.80, etc. These are also known as real numbers.
  • The short form of a floating point is float.
  • The following table shows different types of floating points:

  • In exponential notation, numbers can also be represented. For example, 12345 can be written as 1.2345 x 10⁴. so in a computer program, we can represent it as 1.2345e⁴. Similarly, 0.0098765 is represented in exponential notation as 9.8765e⁻³.

Character

  • It is a data type that is used to define a variable that can store only a single character.
  • It takes 1 byte in memory.
  • The short form of character is char.
  • The variable of type char can store a lower case letter, upper case letter, a digit, or a special character.
Example: ‘a’, ‘+’, ‘W’, ‘8’, ‘%’ etc.

3.2.4 The Constant Qualifier (const)

  • It is used to define a variable whose value cannot be changed throughout the program.
  • When the const qualifier is used with a variable; it no longer remains a variable because its value will not be changed.
  • It has the following syntax:
                    const data-type variable_name = value;

For example:
const int age = 24;
const float length = 7.5;

3.2.5 Variable Declaration and Initialization

Variable Declaration

  • The process of specifying the variable name and its data type is called variable declaration.
  • C++ is a typed language which means that all variables must be declared before they are used in the program.
  • C++ compiler will give an error if an undeclared variable is used in a program.

The general syntax to declare a variable is:

                                                data_type    variables;

where “type” specifies the data type of variable which may be int, float, double, char, etc. “variables” specify the list of variable names of the same data type separated by commas.


Example:
                                                    int sum;

The above declaration statement tells the compiler that the variable name is “sum” and its data type is “int”.

A list of variables of the same data type can be declared in a single declaration statement i.e.
                                            float a, b, c, d, e;

Variable Initialization

  • The process of assigning a value to a variable at the time of declaration is known as variable initialization.
  • The equal sign “=“ is used to initialize a variable.
  • When a variable is declared, the compiler allocates memory location which contains some data that is meaningless for the program. It is known as garbage value which may produce unexpected results.
  • All variables should be initialized to avoid this problem.
  • The syntax of initializing a variable is as follows:
                                    Data_type variable_name = value;

Example:
                int n = 100;
                float average = 34.55;


3.2.6 Type Casting

It is used to convert a variable from one data type to another data type during program execution. There are two types of type casting:

1. Implicit Type Casting:

Implicit type casting is performed automatically by the compiler to convert a data type to another data type.

2. Explicit Type Casting:

  • Explicit type casting is performed by programmer. 
  • The programmer defines the data type in parenthesis before the variable or expression as follows:
                                        (type) expression

3.3 Input / Outpu Handling

  • Providing data into a program from an outside source is called as INPUT.
  • Displaying data on screen or save in a file on a storage device is called OUTPUT.
  • In C++, input/output is performed by using a stream.
  • A stream is a sequence of data that flows in and out of the program.
  • cin and cout are the statements for performing I/O operations. They are present in iostream.h header file.


3.3.1 The cout Statement

  • It is used to display text or values on the screen.
  • Syntax:
                    cout<<“character string”/variable;
  • “<<“ is called the insertion operator which displays the contents of the character string or the value stored in a variable on the screen.
  • The insertion operator may be used more than once in a single statement.
Example

#include <iostream.h>
#include <conio.h>
void main()
{
            crlscr();
            int a=12;
            cout<<“The value stored in a is “<<a;
            getch();
}



3.3.2 The cin Statement:

  • It is used to input data from the keyboard and assign it to a variable.
  • Syntax:
                    cin>>variable;
  • “>>” is called an extraction operator.
  • cin causes the program to wait for the user to input data and assign the entered data to the variable.
Example

#include <iostream.h>
#include <conio.h>
void main()
{
        clrscr();
        int n;
        cout<<“Enter an integer: “;
        cin>>n;
        cout<<“The number you typed is “<<n;
}


3.3.3 The getch() function:

  • It is used to read a single character without waiting for the Enter key to be pressed.
  • This function uses the conio.h header file.

The getche() function:

  • It is used to read a single character without waiting for the enter key and display the input character.
  • The letter e means echo.

The gets() and puts() Functions:

– These functions are used to handle input/output of character strings.
– gets() function is used to input a string from a keyboard.
– puts() function is used to display the string on the screen.

3.3.4 The Escape Sequence

  • Escape Sequence are the special characters which are used to specify the format of output to be displayed on the monitor.
  • It begins with a backslash “\” followed by a single character.
  • These characters are not displayed in the output.
  • It is called an escape sequence because the backslash causes an escape from the normal way characters are interpreted in C++ programming language.

3.3.5 Commonly Used Escape Sequences


3.3.6 The Programing with I/O Handling Function

Program 1: The following program reads three integers and prints their sum and product. 

#include <iostream.h>
#include <conio.h>
void main()
{
        int x,y,z,sum.prod;
        cout<<“\nEnter first number: “;
        cin>>x;
        cout<<“\nEnter second number: “;
        cin>>y;
        cout<<“\nEnter third number: “;
        cin>>z;
        sum=x+y+z;
        prod=x*y*z;
        cout<<“\nSum="<<sum;
        cout<<“\nProduct="<<Prod;
        getch();
}

The execution of the program is shown below.
Enter first number:3
Enter second number:4
Enter third number:5
Sum=12
Product=60

Note: When this program is executed, it prompts the user to enter three numbers. The user enters the numbers, 3,4, and 5 separated by space, and presses the Enter key. The program calculates the sum and product and displays on the screen.

Program 2: The following program reads the base and height of a triangle and prints the area using floating-point values.

#include <iostream.h>
#include <conio.h>
void main()
{
        float base,height,area;
        cout<<“\nEnter the base: “;
        cin>>base;
        cout<<“\nEnter the height: “;
        cin>>height;
        area=(base*height)/2;
        cout<<“\nThe area of triangle is "<<area;
        getch();
}

In this program, two separate input statements are used for reading the values for the variable and height. the execution of the program is shown below"
Enter the base:4.5;
Enter the height:6.2;
The area of the triangle is 13.95

3.3.7 The Manipulators endl and setw

A manipulator is a command in C++ that is used for formatted output.

endl Manipulator:

The endl manipulator causes a linefeed in the cout statement so that the subsequent text is displayed on the next line.

setw Manipulator:

  • It is used in the output statement to set the minimum field width.
  • The number of columns used to display a value on the screen is called field width.
  • It has the general form:
                                        setw(n)
  • n is an integer value which defines a number of columns within which a number or text is to be printed.

EXAMPLE


3.4 Operators in C++:

Operators are the symbols that are used to perform certain operations on data.

3.4.1 Types of Operator:

  1.  Assignment Operator
  2.  Arithmetic Operator
  3.  Arithmetic Assignment Operator
  4.  Increment and Decrement Operator
  5.  Relational Operator
  6.  Logical Operator
  7.  Ternary Operator

1.  Assignment Operator (=)

Assignment operator = is used in assignment statement to assign a value or computational result to a variable.

Syntax:

Variable = expression;

Example:
1. A = 100;
2. C = A + B;
3. X = Y;

2. Arithmetic Operators

  • Those operators which are used to perform mathematical operations on numeric data values are called Arithmetic Operators.
  • Basic arithmetic operators are:


3.  Arithmetic Assignment Operators

C++ language provides assignment operators that combine assignment operators with arithmetic operators which are used to perform mathematical operations.

Syntax:

variable op= expression;

Where op can be any mathematical operator.

Example:

1. A += 10; is equivalent to A = A + 10;
2. A – = 10; is equivalent to A = A–10;
3. A *= 10; is equivalent to A = A * 10;
4. A /= 10; is equivalent to A = A / 10;
5. A %= 10; is equivalent to A = A % 10;

4(a) Increment Operator

  • The increment operator is used to increase the value of a variable by 1.
  • It is denoted by the symbol ++.
  • It is a unary operator i.e. it works with one operand.
Increment operator can be used in two forms:
  1. Prefix form: The increment operator is written before the variable i.e. ++y;
  2. Postfix form: The increment operator is written after the variable i.e. y++;

4(B) Decrement Operator

  • The decrement operator is used to decrease the value of a variable by 1.
  • It is denoted by the symbol --.
  • It is a unary operator i.e. it works with one operand.
The decrement operator can be used in two forms:
  1. Prefix form: The decrement operator is written before the variable i.e. --y;
  2. Postfix form: The decrement operator is written after the variable i.e. y--;

Difference between Prefix & Postfix of increment/decrement operator

  • When these operators are used independently, prefix and postfix form work similarly i.e. the result of A++ and ++A is the same.
  • But when these operators are used in a larger expression with other operators than they work differently i.e. A = --B and A = B-- are different.
  • In prefix form, the statement A = ++B works in the following manner:
                – It increments the value of B by 1
                – It assigns the value of B to A.
  • In postfix form, the statement A = B++ works in the following manner:
                – It assigns the value of B to A
                – It increments the value by 1.

5. Relational Operators:

  • The relational operators are used to compare different data values.
  • They produce results as TRUE or FALSE.
  • They are used to specify the conditions in the program.
  • They are also called comparison Operators as they test conditions that are either TRUE or FALSE.



6. Logical Operators

Logical Operators are used to evaluate compound condition i.e. a statement consists of more than one condition. 
Following are the logical operators used in C language.

1.  AND operator (&&):

It is used to evaluate two conditions. It returns TRUE if both conditions are TRUE and returns FALSE if both or any one condition is FALSE.

Examples:
        (A < 10) && (B>50)
        (Result ==“PASS”) &&(Percentage > 70)


2.  OR operator (||):

It is used to evaluate two conditions. It returns TRUE if both or any one condition is TRUE and returns FALSE if both conditions are FALSE.

Examples:
        (A < 50) || (B > 50)

3.  NOT operator (!):

It is used to reverse the result of a condition. It returns TRUE if the condition is FALSE and returns FALSE if the condition is TRUE. 

Example:
        !(A == B)


7. Ternary Operator

  • It is used to return one of two values depending on the result of a condition.
  • It is also known as a conditional operator.
  • The condition operator has a general form:
                (condition)? Expression 1: Expression 2;

  • Condition evaluates to either true or false
  • If it is true the entire conditional expression takes on the value of expression1.
  • If it is false the entire conditional expression takes on the value of expression2.

Example:

#include <iostream.h>
#include <conion.h>
void main()
{
        clrscr();
        int x,y,k;
        x=15;
        y=10;
        k= (x>y)? x+y: x-y;
        cout<<“the value of k is “<<k;
        getch();
}


3.4.2 UNARY, BINARY AND TERNARY OPERATORS

There are three types of operators in C++ which are unary, binary, and ternary operators.

The operator that works on a single operand is known as a unary operator. Unary operators are -, ++, --, and the logical operator !.

Some examples of unary operators are
a= -b;
k++;
--X;
The operators that work on two operands are known as binary operators. Binary operators are - ,+,*,/, %, and logical operators && and II.

Some examples of binary operators are
a=b+c; 
z=x*y;
k=d%e;

The conditional operator (?;) is known as a ternary operator since it has three parts. These three parts are a condition and two expressions. The condition is evaluated and based on its result one of the two expressions is executed.

3.4.3 Order of Precedence of Operator 

  • The order in which different types of operators in an expression are evaluated is known as operator precedence.
  • It is also called the hierarchy of operators.
  • If an expression contains different types of operators, the operator with higher precedence is evaluated before the operator with lower precedence.


Example No. 1.


#include <iostream.h>
#include <conio.h>
void main()
{
        int num1, num2, total;
        num1= 13;
        num2 = 20;
        total = num1 + num2;
        cout<<”The total of “<<num1<<” and “
        <<num2<<” is “<<total<<endl;
        getch();
}


Example No. 2.


#include <iostream.h>
#include <conio.h>
void main()
{
        int n;
        n=10;
        cout<<”The initial value of n is “<<n<<endl;
        n++;
        cout<<”The value of n is now “<<n<<endl;
        n++; n++;
        cout<<”The value of n is now “<<n<<endl;
        n--;
        cout<<”The value of n is now “<<n<<endl;
        getch();
}

3.4.4 Expression in C++

  • A combination of operators and operands is called Expression.
  • Operands may be variables, constants, or both.

1. Arithmetic Expression:

  • A combination of Arithmetic operators and numeric constants/variables is called an arithmetic expression.
  • In a C program, the arithmetic expression is used to calculate the value of an arithmetic formula. 
Examples:
         a + b;
         34 – 22;

2. Relational Expression:

  • An expression that contains a relational operator to compare values of the same type is called a relational operator.
  • It is used to create conditions in programming.

3. Compound or Logical Expression:

  • An expression that combines two or more conditions using a logical operator is called a compound expression.



************************************
👉👉👉 Computer Science 12th Class Notes (Main Page)

************************************


************************************
Shortcut Links For:

1.  5th Class All Subjects Notes

2.  8th Class All Subjects Notes

3.  Easy English Grammar Notes



1. Website for School and College Level Physics   
2. Website for School and College Level Mathematics  
3. Website for Single National Curriculum Pakistan - All Subjects Notes 

© 2023 & onwards Academic Skills and Knowledge (ASK  

Note:  Write me in the comments box below for any query and also Share this information with your class-fellows and friends.



Post a Comment

0 Comments

cwebp -q 80 image.png -o image.webp