Chapter-3 (12)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

1

Chapter No. 3
Object Oriented Programming in C + +
MCQs ………………….………………………………………… Page 2

Short Questions/Answer ………………………………. Pages 3 - 18

Long Questions …………………………………………….. Pages 19–22

Lab Activities……..………………………………………….. Pages 23–24

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
2

Multiple Choice Questions (MCQs)


Note: - Select the best answer for the following MCQs.

i. Which of the following is ignored during program execution?


A. Reserved word B. Constant
C. Comment D. const qualifier
ii. What is the range of unsigned short integer?
A. -2147483648 to 2147483647 B. 0 to 4294967295
C. -32768 t0 32767 D. 0 to 65535
iii. In C ++ the expression sum = sum + n can also be written as :
A. sum + = n B. sum = n ++
C. sum = + n D. n + = sum
iv. Which of the following is equal to operator?
A. + = B. ==
C. = D. =+
v. Which of the following is an arithmetic operator?
A. && B. %
C. < = D. ++
vi. Which of the following operators is used to form compound condition?
A. Arithmetic operator B. Assignment operator
C. Relational operator D. Logical
vii. The number of bytes reserved for a variable of data type ‘float’ is :
A. 2 B. 4
C. 6 D. 8
viii. How cursor is moved to the next tabular position for printing data?
A. By using reserved word B. By using manipulator
C. By using escape sequence D. By using header file
ix. What will be the value of d = 11/2?
A. 1 B. 5
C. 5.5 D. 6
x. Which of the following is not an example of logical operator?
A. AND B. OR
C. NOT D. !=

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

Short Questions/Answers (Q/A)


1. Briefly describe C ++ language.

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.

2. What is a computer program?

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.

3. Define source code and object code.

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.

4. What is the purpose of using header file in program?

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.

# include <name of header file.h>

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.

Header File Purpose


iostream.h Stands for standard input output stream and provides basic input/output
operations such as cin and cout.
conio.h Stands for console input/output and manages input/output console
applications like getch ( ) and grtche ( ).
math.h Provides basic mathematical operations such as sqrt ( ), pow ( ) etc.
string.h Provides to manipulate string functions like strcmp ( ), strcpy ( ) etc.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
4

iomanip.h Provides manipulator function such as setw ( ) and setprecision ( ) etc.


time.h Provides date and time operations.

6. What is preprocessor directive?

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.

Examples of reserved words are int, cout, for etc.

8. Describe the structure of a C++ program.

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.

Example is cout <<” Thanks”;

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:

// This is my first C++ program

 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*/

11. Differentiate between constant and variable.

Ans: - The differences between constant and variable are as follows.

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

Ans: - Valid variable names: - a123 _abcd f3ss1 net_weight

Invalid variable names: -

5hml because a variable cannot start with a digit.

tot.al because a variable cannot have a dot/period (.) in it.

c$avg because $cannot be used in variable name.

cout because reserved words cannot be used as variable name.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
6

13. What is data type?

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;

The data types used in C++ are:

 Integer
 Floating –point
 Character

14. Briefly describe integer data type.

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.

Integer Type Number of Bytes Range of Numbers


Int 4 -2147483648 to 2147483647
unsigned int 4 0 to 4294967295
short int 2 -32768 to 32767
unsigned short int 2 O to 65535
long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295

(Note: The use of word int becomes optional when data types short, signed, unsigned or long etc are
used.)

15. Briefly describe Floating-Point data type.

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

Integer Type Number of Bytes Range of Numbers


Float 4 -3.4-38 to 3.438 (with 6 digits of precision)
double float 8 -1.7-308 to 1.7308 (with 15 digits of precision)
long double float 10 -1.7-4392 to 1.74392 (with 15 digits of precision)

(Note: The use of word float becomes optional when data types double or long double are used.)

16. Briefly describe character data type.

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=’+’;

17. What is the use of const qualifier (Constant qualifier)?

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:

const data-type variable = constant;

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:-

const int pi = 3.142;

const float radius = 7.7;

18. What do you mean by variable declaration and initialization?

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

int a=10, b=5, c=8;


float l=10.5, w=3.8;
char ch=’D’;
19. What is the use of cout statement in C++? Describe with example.

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)

Ans: - # include <iostream.h>


Output:-
# include <conio.h>
void main (void) Enter base of triangle = 5.6

{ Enter height of triangle = 8.4

clrscr ( ); Area of triangle = 47.04

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

23. Differentiate between getch ( ) and getche ( ) functions.


Ans: - The differences between getch ( ) and getche ( ) function are as follows.
getch ( ) function getche ( ) function
 getch stands for get character.  getche stands for get character and e
for echo.
 It does not display the character  It accepts and displays the character
until Enter key is pressed. without pressing Enter key.
 Example:  Example:
char ch; char ch;
ch = getch ( ); ch = getche ( );

24. Differentiate between gets ( ) and puts ( ) functions.

Ans: - The differences between gets ( ) and puts ( )functions are as follows.

gets ( ) function puts ( ) function


 gets stands for get string.  puts stands for put string.
 It is used to enter string.  It is used to display/output string.
 Example:  Example:
char str[50]; char str[50];
cout << “Enter a string : “; cout << “Enter a string : “;
gets(str); gets(str);
cout << “\n You typed : “;
puts(str);

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.

Escape Sequence Purpose


\a Produces alert (beep) sound.
\b Moves cursor backward by one position.
\n Moves cursor to the beginning of next line.
\r Moves cursor to the beginning of current line.
\t Moves cursor to the next horizontal tabular position.
\\ Produces a backslash.
\’ Produces a single quote.
\” Produces a double quote.

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
11

26. What is an operator? List different types of operators used in C++.

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.

The following types of operators are used in C++.

 Assignment operator
 Arithmetic operators
 Arithmetic assignment operators
 Increment/Decrement operators
 Relational operators
 Logical operators
 Ternary operator

27. What is an assignment 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;

Variable is to be assigned a value.


= is used to assign a value to the variable.
Expression can be a constant, variable or arithmetic 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.

Different arithmetic operators used in C++ are as follows.

Operator Operation Description Example


+ Addition Adds two values 9 + 4 will give result 13
- Subtraction Subtracts one value from another 9 - 4 will give result 5
* Multiplication Multiplies two values 9 * 4 will give result 36
/ Division Divides one value by another value
9 / 4 will give result 2
9.0 / 4 or 9 / 4.0 or
9.0 / 4.0 will give result 2.5
% Remainder division Gives remainder of division of two 9 % 4 will give result 1
(Modulus) integers

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
12

29. Briefly describe arithmetic assignment operators.

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;

Variable is be assigned a value.


Op can be any arithmetic operator.
Expression can be a constant, variable or arithmetic expression.
Different arithmetic assignment operators used in C++ are as follows.

Operator Example Equivalent arithmetic operator


+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b

30. Briefly describe increment and decrement operators.

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: -

n = n + 1; is equivalent to n++; or ++n;

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;

31. Differentiate between prefix and postfix increments.

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.

Prefix increment operator Postfix increment operator


 Operator is written before the Operator is written after the variable. For
variable. For example ++ n;. example n ++ ;.
 In large expressions, It increments  In large expressions, It assigns the

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

32. Differentiate between prefix and postfix decrements.

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.

Prefix decrement operator Postfix decrement operator


 Operator is written before the Operator is written after the variable. For
variable. For example ++ n; example n ++ ;
 In large expressions, it decrements  In large expressions, it assigns right
the value of right side variable and side variable to left side variable and
then assign to left side variable then decrements 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=9 x = 10
y=9 y=9

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
14

33. Briefly describe relational operators.

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.

Operator Definition Example (when a=30, b=50)


> Greater than a>b will produce result False
< Less than a<b will produce result True
>= Greater than or equal to a>=b will produce result False
<= Less than or equal to a <= b will produce result True
== Equal to a==b will produce result False
!= Not equal to a != b will produce result True

34. Briefly describe logical 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.

C++ language provides the flowing three types of logical operators.

 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.

Expression -1 Expression - 2 Expression -1 && Expression -2


True True True
True False False
False True False
False False False
Examples: -

(x > = 1) && (x < = 10)

(ch> = ‘a’) && (ch< = ‘z’)

 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.

Expression -1 Expression - 2 Expression -1 || Expression -2


True True True
True False True
False True True
False False False
Examples: -

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
15

(x >y) || (z= = 10)

(ch= = ‘a’) || (ch= = ‘u’)

 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)

35. Briefly describe Ternary operator.

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? Expression -1: Expression – 2;

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.

Relational Operators Logical Operators


 These are used to compare two  These are used to combine two
values. or more relational expressions.

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)

37. Differentiate among unary, binary and ternary operators.

Ans: - The differences among unary, binary and ternary operators are given below.

Unary Operator Binary Operator Ternary Operator


 It operates on single  It operates on two  It operates on three
operand. operands. operands.
 Unary operator include  Binary operators include  ? and : are used as part
preceding minus ( - ), ++, - +, -, *, /, %, &&, ||, >, < of ternary operator.
- and !. = etc.
 Examples:  Examples:  Example:
a = - b; a = a + b; marks = 50;
n ++; c = a % b; marks>= 40 ? cout
- -x; a>b <<“Pass” : cout <<”Fail”;
!p; (x > y) && (x > z)
etc etc

38. What will be the output of the following statements?


a) cout <<”17/3 is equal to “<<17/2;
b) cout <<”10.2/4 is equal to “<<10.2/4;
c) cout <<”40/5%3*7 is equal to ”<<(40/5%3*7);

Ans: - Outputs are:

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

39. Evaluate the following integer expressions.


a) 3+4*5 b) 4*5/10+8 c) 3 * (2 + 7 * 4)
d) 20 – 2 / 6 + 3 e) (20 – 2) / (6 + 3) f) 25 % 7

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: -

a) 10.0 + 15 / 2 + 4.3 b) 10.0 + 15.0 / 2 + 4.3 c) 4 / 6 * 3.0 + 6


Solution:- 10.0 + 15 / 2 + 4.3 Solution:- 10.0 + 15.0 / 2 + 4.3 Solution:- 4 / 6 * 3.0 + 6
=> 10.0 + 7 + 4.3 => 10.0 + 7.5 + 4.3 => 0 * 3.0 + 6
=> 17.0 + 4.3 => 17.5 + 4.3 => 0 + 6
=> 21.3 => 21.8 => 6

41. What will be the output of the following program?

# 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

42. What will be the output of the following program?

# 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

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 ( );
}
Ans: -

The initial value of n is 10

The value of n is now 11

The value of n is now 13

The value of n is now 12

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).

The following are rules for specifying variable names.

 The first character of a variable name must be an alphabet or underscore ( _).


 The characters allowed in variable name are underscore ( _ ), digits (0 to 9), upper-case
letters (A to Z) and lower-case letters (a to z).
 Special symbols such as =, &, @, # are not allowed.
 Blank spaces or commas are not allowed.
 Reserved words such as void, do, cout etc are not allowed to be used as a variable name.

(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)

2. What is constant? Explain different types of constants.

Ans: - Constant: - A constant is a value that does not change during execution of program.

C++ has the following types of constants.

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.

4. Define endl and setw manipulators and give an example of each.

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.

Example: - The following program illustrates the use of endl manipulator.

# 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.

Example: - The following program illustrates the use of setw manipulator.

# include <iostream.h> Output:-


# include <conio.h> Product Price
void main (void) Hard Disk 8540
{ Mouse 325
clrscr ( ); Computer 27800
int p1 = 8540, p2 = 325, p3 = 27800;
cout <<” Product ”<<setw (10) << “Price”<<endl;
cout <<” Hard Disk ”<<setw (10) << “p1”<<endl;
cout <<” Mouse ”<<setw (10) << “p2”<<endl;
cout <<” Computer ”<<setw (10) << “p3”<<endl;
getch ( );
}

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.

Precedence Operator (s) Description


1 *, / , % Multiplication, Division and Remainder
2 +,- Addition and Subtraction
3 <,<=,>,>= Less than, Less than or equal to, Greater than, Greater
than or equal to
4 == , ! = Equal to and Not equal t
5 ! Logical NOT
6 && Logical AND
7 || Logical OR
8 =,*=,/=,%=,==,-= Assignment Operators

Second Year Computer Notes By Riaz Khattak APS & C (Boys) Peshawar
22

6. What is an expression? Describe different types of expressions in C++.

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.

Different types of expressions in C++ are as follows.

 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: -

(ch>= ‘a’) && (ch<= ‘z’)


!(x = 40)

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

You might also like