Chapter-3 (12)
Chapter-3 (12)
Chapter-3 (12)
Chapter No. 3
Object Oriented Programming in C + +
MCQs ………………….………………………………………… Page 2
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
2
Answers
i. C ii. D iii. A iv. B v. B
vi. D vii. B viii. C ix. B x. D
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
3
Ans: - C ++ is general purpose high level programming language developed by Bjarne Stroustrup in
early 1980s at Bell Laboratories. It is an improved version of C language. C ++ supports modern
programming techniques like Object Oriented Programming (OOPs). It is commonly used for
developing high performance commercial software, games and graphics related programs.
Ans: - A computer program is a set of instructions that performs a specific task when executed by a
computer. All tasks performed by computers are controlled by computer program. For example MS-
Word is a program that allows computer users to create documents. Programs written in high level
languages must be translated to machine language instructions by compiler/interpreter before
execution because computer can only understand the language of 0’s and 1’s.
Ans: - Source code: - A program written by a programmer in any high level language such as C++ is
called source program. It is human readable.
Object code: - The code that is generated by the compiler from source code is called object code. It
is also known as machine code Computer understands object code directly.
Ans: - Header files contain information that is required by the program in which they are used. The
C++ contains many header files. Each header file contains different types of pre-defined functions
and objects. Many header files can be included in one program. Header file has .h extension.
Preprocessor directive is used to include header file at the beginning of a program. Preprocessor
have the following general syntax.
Examples:
# include <iostream.h>
# include <conio.h>
5. Describe the purpose of some commonly used header files.
Ans: - Some commonly used header files and their purpose are described below.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
4
Ans: - Preprocessor directive is an instruction given to the compiler before the actual program. It
starts with # (hash) symbol and the keyword include. It is written at the start of program to include
header files.
Examples: - # include <iostream.h
# include pi = 3.142;
7. Define reserved words and give three examples.
Ans: - In programming languages reserved words are special words which are reserved for specific
purpose in a program. These cannot be used as variable names. All the reserved words are written in
lower-case letters. Reserved words are also called keywords.
Ans: - The format of writing program in C++ is called its structure. A C++ program consists of the
following parts.
Preprocessor directives
main ( ) function
Body of main function (Program body)
Preprocessor directives: - The preprocessor directive is used to include header files in the
program. For example # include <iostream.h>
main ( ) function: - The main ( ) function is the starting point of a C++ program. Every C++ must
have main ( ) function. When the program is run, the control enters into main ( ) function and
starts executing its statements. For example void main (void)
Body of main function (Program body):- C++ statements are written between two curly bracket
{ }. Body of C++ statements consists of many statements in which each statement performs a
specific task when the program is executed by CPU. For example:
{
cout<< “Thanks”;
getche ( );
}
9. What do you mean by statement terminator in C++program?
Ans: - The statement terminator/delimiter indicates the end of a C++ statement. The semicolon (;)
is used as statement terminator in C++. All statements must end with a semicolon. The compiler
generates a syntax error if the statement terminator is not used at the end of a statement.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
5
10. Why comments are used in C++ program? Briefly describe its different types.
Ans: - Comments: - Comments are explanatory statements in the program that help user to
understand the source code. The comments can be inserted anywhere in the program. Comments
can be used more than one time in a program. Comments are not executable statements and the
compiler ignores them during execution of the program. Comment has two types.
Single-line comments (//):- The comments on single line are added by using // (double slash).
Anything written on the right side of double slash is considered as comments and is ignored
during execution. For example:
Multi-line comments (/* and */):- This type of comment is used for entering multiple line
comments in a program. The /* is used at the beginning and */ at the end. Anything written in
/* and */ is considered as comment and is ignored during execution. For example:
/* Thanks
Good Bye*/
Constant Variable
A constant is a value that does not A variable stores data which may
change during execution of program. change during execution of program.
It can be a number, a character or a It can store numeric constant,
character string. character constant or string constant.
Examples are 42, 7.25, ‘a’ etc. Examples are name[10], sum etc
12. State whether the following variable names are valid or invalid. State the reason for invalid
variable names?
a123 _abcd 5hml tot.al
f3ss1 c$avg netw_wight cout
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
6
Ans: - The data type specifies the type of data that can be stored in a variable. Every data type has
a range of values and requires different amount of memory. In C++ programs, data type of a variable
must be defined before assigning it a value. For example:
Int a,b,c;
Integer
Floating –point
Character
Ans: - Integer data type is used to define integer variables. An integer variable only stores whole
numbers such as 10, -45 etc. It cannot store numbers with fractional/decimal part. Integers
represent the values that are counted such as number of students in a class. It is represented by int.
e.g.
int a, b, c;
The following table shows the integer types, number of bytes occupied in memory and the range of
values it can store.
(Note: The use of word int becomes optional when data types short, signed, unsigned or long etc are
used.)
Ans: - Floating-point data type is used to define floating-point (real) variables. A floating-point
variable stores the numbers with fractional/decimal part such as 3.75, -34.83 etc. It is represented
by float. e.g.
float a, b, c;
The following table shows the floating-point types, number of bytes occupied in memory and the
range of values it can store.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
7
(Note: The use of word float becomes optional when data types double or long double are used.)
Ans: - Character data type is used to define character variables. The keyword char is used to
represent character data type in C++. A character variable takes one (1) byte of in memory. A
character variable can store a single character such as a small/capital alphabet, digit or special
character etc. Character stored in character variable is written in pair of single quote marks. e.g.
char a, b;
a=’5’;
b=’+’;
Ans: - In C++ language, const defines a variable whose value cannot be changed throughout the
program. When the const qualifier is used with a variable, then it does not remain a variable because
its value will not be changed. A variable with the const qualifier must be assigned some value. It
general syntax is:
Here, const is a reserved word, Data-type can be int, float, char etc., variable is any valid variable
name and constant is any valid constant value.
Example:-
Ans: - Variable declaration: - Declaration of variable means to specify the data type of variable. It
allows the compiler to decide how many bytes should be set aside in memory for storing the value of
variable. Ever variable must be declared before use. For example:
int a, b, c;
float l, w;
char ch;
Variable initialization: - Initializing a variable means assigning it an initial value. A variable may be
initialized at the beginning of a program when it is declared. For example:
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
8
Ans: - The word cout stands for console output. The cout statement is used to display text or
values on screen. Its general syntax is:
cout <<”String”/Variable;
Here
cout is a reserved word used to display output on screen.
<< is called insertion operator. It directs the contents of string or the value of variable to the screen.
The insertion operator may be used more than once in a single cout statement.
String/Variable indicates the required output to be displayed. String can be displayed with no
change while the variables is replaced by its value
Example:-
a=10;
cout<<” The value of a = “<<a;
Output:-
The value of a = 10
20. What is the use of cin statement in C++? Describe with example.
Ans: - The word cin stands for standard input. The cin statement is used to input data from the
keyboard and assign it to one or more variables.
cin>>Variable;
Here
cin is a reserved word used to get standard input.
>> is called extraction operator. It gets the input from cin after running the program.
Variable stores the input value.
Example:-
cin>>a;
Output:-
The above statement will get value from keyboard after running the program and will store it in
variable a.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
9
21. Write a program that reads three integers and prints their sum and product.(page No. 53)
Ans: - .
# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( ); Output:-
int a, b, c, sum, pro; Enter first number = 5
cout<<” \n Enter first number = “; Enter second number = 6
cin>> a; Enter third number = 4
cout<<” \n Enter second number = “; Sum = 15
cin>> b; Product = 120
cout<<” \n Enter third number = “;
cin>> c;
sum = a+b+c;
pro = a*b*c;
cout<<” \n Sum = “<<sum;
cout<<” \n Product = “<<pro;
getch ( );
}
22. Write a program that reads the base and height of a triangle and prints area using floating
point values. (Page No.53)
float b, h, area;
cout<<” \n Enter base of triangle = “;
cin>> b;
cout<<” \n Enter height of triangle = “;
cin>> h;
area = (b * h)/2;
cout<<” \n Area of triangle = “<<area;
getch ( );
}
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
10
Ans: - The differences between gets ( ) and puts ( )functions are as follows.
25. Why escape sequence is used? Give explanation of different escape sequences.
Ans: - Escape sequence are special characters used to control the format of output. These
characters are used in the cout statement. These are not displayed in the output. An escape
sequence begins with a backslash ( \ ) followed by a code character. It is called escape sequence
because the backslash causes an escape from the normal interpreting of the characters.
Most commonly used escape sequences and their purposes are described below.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
11
Ans: - An operator is a symbol that tells the computer to perform a specific task. C++ provides a
variety of operators. Different operators are used to perform different operations on data. For
example + operator is used to add two numbers.
Assignment operator
Arithmetic operators
Arithmetic assignment operators
Increment/Decrement operators
Relational operators
Logical operators
Ternary operator
Ans: - An assignment operator is used to assign a value to a variable. The equal sign symbol (=) is
used as assignment operator in C++. It has the following general syntax.
Variable = Expression;
Examples: -
A = 20;
Sum= a + b;
Z= (a = b)/2;
28. Briefly describe arithmetic operators.
Ans: - Arithmetic operators are used to perform arithmetic operations on data which includes
addition, subtraction, multiplication, division and remainder.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
12
Ans: - Arithmetic assignment operators are used to combine assignment operator with arithmetic
operators. These operators are used to perform arithmetic operations more easily. Its general syntax
is:
Variable Op = expression;
Ans: - Increment operator: - Increment operator (++) is used to add one (1) to the value stored in a
variable. Its purpose is to shorten the expression.
Example: -
Decrement operator: - Decrement operator (--) is used to subtract one (1) from the value stored in a
variable. Its purpose is to shorten the expression.
Example: -
n = n - 1; is equivalent to n - -; or - -n;
Ans: - Prefix and postfix increments are same when used independently. For example x ++
and ++ x will produce same result. But these two work differently in large expressions.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
13
the value of right side variable and right side variable to left side variable
then assign to left side variable and then increments the right side
variable.
Example: Example:
y = 10; y = 10;
x = ++ y; x = y ++;
cout<<”\n x = ”<<x; cout<<”\n x = ”<<x;
cout<<”\n y = “<<y;; cout<<”\n y = “<<y;;
Output:- Output:-
x = 11 x = 10
y = 11 y = 11
Ans: - Prefix and postfix decrements are same when used independently. For example x - - and - - x
will produce same result. But these two work differently in large expressions.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
14
Ans: - Relational operators are used to compare two values of the same type. These are helpful in
situations where the flow of program is based on a condition. After evaluation of relational
expression, the result produced is either true or false. These are sometimes called comparison
operators. C++ provides the following six basic relational operators.
Ans: - Logical operators are used in programming to perform a task based on compound condition.
Compound condition is the combination of two or more conditions.
AND (&&) Operator: - Logical AND (&&) operator is used to form compound condition in which
two relational expressions are evaluated. The compound statement evaluates to True if both
conditions are True. It evaluates to False if any one condition is False. The following table shows
all possible results of AND (&&) logical operators for two expressions.
OR (||) Operator: - Logical OR (||) operator is used to form compound condition in which two
relational expressions are evaluated. The compound statement evaluates to True if any one
condition or both are True. It evaluates to False if both conditions are False. The following table
shows all possible results of OR (||) logical operators for two expressions.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
15
NOT (!) Operator: - Logical NOT (!) operator is used with a single expression (condition). It
evaluates to True if the expression is False and vice versa.
The following table shows all possible results for NOT (!) logical operator.
Expression Expression
True False
False True
Example: -
!(x > y)
Ans: - Ternary operator is also called conditional operator. It evaluates a condition and returns one
of the two values based on the result of the condition. It is very useful in situation where the
programmer needs to choose one of two options depending upon a single condition. It is equivalent
to if-else structure. It has the following general syntax.
Condition will be evaluated first. If it is true then Expression – 1 will be executed otherwise
Expression –2 will be executed.
Example:-
# include <iostream.h>
# include <conio.h> Output:-
void main (void) Value of c = - 40
{
clrscr ( );
int a, b, c;
a = 50; b = 90;
c = (a >b) ? a + b : a – b;
cout<<” \n Value of c = “<<c;
getch ( );
}
36. Differentiate between relational and logical operators.
Ans: - The differences between relational and logical are given below.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
16
The six relational operators are >, The three logical operators are
<, >=, <=, ==, !=. &&, ||, !.
Examples: Examples:
Marks >= 40 (ch>= ‘a’) && (ch<= ‘z’)
a == b !(x = =40)
Ans: - The differences among unary, binary and ternary operators are given below.
a) 17/3 is equal to 5
b) 10.2/4 is equal to 2.55
c) 40/5%3*7 is equal to 14
Ans: -
a) 3 + 4 * 5 b) 4 * 5 / 10 + 8 c) 3 * (2 + 7 * 4)
Solution:- 3 + 4 * 5 Solution:- 4 * 5 / 10 + 8 Solution:- 3 * (2 + 7 * 4)
=> 3 + 20 => 20 /10 + 8 => 3 * (2 + 28)
=> 23 => 2 + 8 => 3*30
=> 10 => 90
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
17
d) 20 – 2 / 6 + 3 e) (20 – 2) / (6 + 3) f) 25 % 7
Solution:- 20 – 2 / 6 + 3 Solution:- (20 – 2) / (6 + 3) Solution:- 25 % 7
=> 20 – 0 + 3 => 18 /(6 + 3) => 4
=> 20 + 3 => 18 / 9
=> 23 => 2
40. Evaluate the following expressions that have integer and floating-point data types.
a) 10.0 + 15 / 2 + 4.3 b) 10.0 * 15.0 / 2 + 4.3 c) 4 / 6 * 3.0 + 6
Ans: -
# include <iostream.h>
# include <conio.h>
void main ()
{
clrscr ( );
int num1, num2, total;
num1 = 13;
num2 = 20;
total = num1 + num2;
cout<<”The total of “<<num1<<” and “<<num2<<” is “<<total<<endl;
getch ( );
}
Ans: - The total of 13 and 20 is 33
# include <iostream.h>
# include <conio.h>
void main ()
{
clrscr ( );
int n;
n= 10;
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
18
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
19
Long Questions/Answers
1. Define variable and write the rules for specifying variable names.
Ans: - Variable: - A variable is a name of memory location where data is stored. It is used in
computer programs to store values of different data types. The data stored in a variable may change
during program execution. The variable can be of type int (integer), float or char (character).
(Note: Be remember that C/C ++ is case sensitive language which consider lower-case letters
different from upper-case letters. e.g. sum is different from SUM or Sum)
Ans: - Constant: - A constant is a value that does not change during execution of program.
a) Numeric Constants
b) Character Constants
c) String Constants
a) Numeric Constants: - Numeric constants consist of numbers. It can be further divided into
integer and Floating Point constants.
Integer Constants: - Integer constants are numeric values without fraction or decimal point.
Both negative and positive numbers can be used as integer constants. If no sign is used, the
value is positive by default. Examples are 78, -98, +10087 etc
Floating Point Constants: - Floating point (Real) constants are numeric values with fraction or
decimal point. Both negative and positive numbers can be used as floating point constants. If no
sign is used, the value is positive by default. Examples are 78.45, -98.39, +1008.97 etc.
b) Character Constants: - Any character written within single quote is known as character constant.
All alphabetic characters, digits and special symbols can be used as character constants. The
maximum length of a character constant is one (1) character. Examples are ‘A’, ‘d’, ‘5’, ‘+’ etc.
c) String Constants: - A collection of characters written in double quotes is called string or string
constant. It may consist of any alphabetic characters, digits and special symbols. Examples are
“Pakistan”, “14th August 1947”, “Sector F-5” etc.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
20
3. Why type casting is used? Explain the types of type casting with an example of each type.
Ans: - Type casting is used to convert the data type of a value during execution. There are two
types of type casting. These are implicit type casting and explicit type casting.
Implicit Type Casting: - In Implicit type casting, compiler automatically converts a data type to
another. The operands in arithmetic operation must be of similar type. If it is not so then the
value of lower data type will be converted into higher data type.
Example: - Suppose q is available of type float then q = 15 / 6 ; will produce 2 because an integer
division will be performed on two integer operands (15 and 6) to get 2 which will be implicitly
converted to float value 2.0 and assigned to q.
In case of any one operand or both of type float (15.0 or 6.0 or both), the value of q will be 2.5.
Explicit Type Casting: - Explicit type casting is performed by the programmer. In explicit type
casting, a special cast operator is used to convert one data type into another. The cast operator
tells the compiler to convert the data type of a value. Its general syntax is
(type) Expression;
here
type indicates the data type to which operand is to be converted.
Expression indicates the constant, variable or expression whose data type is to be converted.
Example: - Suppose q is a variable of type float and a, b are variables of types integer. The value
of a is 15 and the value of b is 6 then q = (float) a/b ; will first convert value of a to float i.e. 15.0
and then will divide by value of b (6) to get result 2.5 which will be assigned to q.
Ans: - endl Manipulator: - The word endl stands for end of line. The endl manipulator causes
linefeed in the court statement so that the subsequent text is displayed on the next line. It has the
same function as the \n escape sequence. The endl manipulator can be used by including iostream.h
header file in the program.
# include <iostream.h>
# include <conio.h> Output:-
void main (void)
I am Pakistani
{
I love Pakistan
clrscr ( );
Pakistan Zindabad
cout <<”I am Pakistani”<<endl<<”I love Pakistan”<endl;
cout<<”Pakistan Zindabad”;
getch( );
}
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
21
setw Manipulator: - The word setw stands for set width. It is used in output (cout) statement to set
the minimum field width. It has the following general syntax.
setw ( n);
Here, n indicates the number of columns in which the value is to be displayed. The number or text to
be displayed is right justified within the set field width. It is commonly used to align numbers or text
on output.
5. What is meant by precedence of operators? Write the operators with the highest precedence
at the top and the lowest at the bottom.
Ans: - Precedence of operators means that which operator should be evaluated on priority basis in
an expression. Order of precedence of operators describes the rules according to which operations
are to be performed in an expression. Parentheses are used in expression to change the order of
evaluation of operators specified by operator precedence.
Following is the list of all operators with the highest precedence operators at the top and lowest at
the bottom.
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
22
Ans: - An expression is combination of constants, variables and operators. It returns a single value
when it is executed. The variables and constants in an expression are called operands. An operator is
a symbol that tells the computer to perform certain type of operation on operands.
Arithmetic expression
Relational expression
Logical expression
Arithmetic expression: - An expression that contains constants, variables and arithmetic operators is
called arithmetic expression. These expressions are used to perform arithmetic operations such as
addition, subtraction, division etc.
Examples: -
c = 5/9.0 * (f – 32);
average = sum/3;
Relational expression: - An expression that contains constants, variables and relational operators is
called relational expression. It is used for comparison of values and makes decision based on the
condition. The result of relational expression can be True or False.
Examples: -
ch>= ‘a’
x == 40
Logical expression: - An expression that contains constants, variables and logical operators is called
logical expression. It is used to combine two or more conditions using &&, || or !. Logical expression
is also called compound expression.
Examples: -
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
23
Lab Activities
1. Write a program that reads four integers and prints their sum, product and average.
Ans: -
# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
int a, b, c, d, sum, pro;
float avg;
cout<<” \n Enter first number = “;
cin>> a;
cout<<” \n Enter second number = “;
Output:-
cin>> b;
Enter first number = 5
cout<<” \n Enter third number = “;
Enter second number = 6
cin>> c;
Enter third number = 4
cout<<” \n Enter four number = “;
Enter four number = 3
cin>> d;
Sum = 18
sum = a+b+c+d;
Product = 360
pro = a*b*c*d;
Average = 4.5
avg = sum/4.0;
cout<<”\n Sum = “<<sum;
cout<<”\n Product = “<<pro;
cout<<”\n Average = “<<avg;
getch ( );
}
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
24
2. Write a program that reads length and breadth of a rectangle and prints its area.
Ans: -
# include <iostream.h>
# include <conio.h> Output:-
void main (void)
Enter length of rectangle = 5
{
Enter width of rectangle = 6
clrscr ( );
Area = 30
intl, b, area;
cout<<” \n Enter length of rectangle = “;
cin>>l;
cout<<” \n Enter breadth of rectangle = “;
cin>>w;
area = l*w;
cout<<”\nArea = “<<area;
getche ( );
}
3. Write a program that reads temperature in Fahrenheit and prints its equivalent temperature
in Celsius using the following formula.
c = 5/9 (f-32).
Ans: -
# include <iostream.h>
# include <conio.h>
Output:-
void main (void)
Enter temperature in Fahrenheit scale = 68.0
{
Temperature in Celsius scale = 20.0
clrscr ( );
flaot f, c;
cout<<” \n Enter temperature in Fahrenheit scale = “;
cin>>f;
c = 5/9.0 *(f – 32);
cout<<” \n Temperature in Celsius scale = “<< c;
getch ( );
}
Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar