0% found this document useful (0 votes)
0 views31 pages

Chapter 4

The document contains educational material on control structures in programming, including multiple choice questions, short answers, and programming exercises. It covers various control structures such as sequential, conditional, and iteration, along with their differences and applications. The content is designed for second-year computer students and includes examples and explanations of loops, if statements, and the use of break and continue statements.

Uploaded by

arslan2000888
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views31 pages

Chapter 4

The document contains educational material on control structures in programming, including multiple choice questions, short answers, and programming exercises. It covers various control structures such as sequential, conditional, and iteration, along with their differences and applications. The content is designed for second-year computer students and includes examples and explanations of loops, if statements, and the use of break and continue statements.

Uploaded by

arslan2000888
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

1

Chapter No. 4
Control Structures
MCQs …………………………………………………………… Page 2

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

Long Questions …………………………………………….. Pages 16–23

Lab Activities…………………………..…………………….. Pages 24–31

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. How is a single-statement for loop terminated?


A. with a colon B. with a right brace
C. with a right bracket D. with a semicolon
ii. How is multi-statement for loop terminated?
A. with a colon B. with a right brace
C. with a right bracket D. with a semicolon
iii. Which of the following can be used to replace ternary operator?
A. if statement B. if-else statement
C. else-if statement D. while statement
iv. Which of the following can be used to replace switch statement?
A. if-else statement B. break statement
C. else-if statement D. while loop
v. A while loop is more appropriate to use than a for loop when:
A. the body of loop is to be executed at least once
B. the termination condition occurs unexpectedly
C. the program executes at least once
D. when the number of iterations is known in advance
vi. In which situation a do-while loop is more appropriate to use?
A. when the body of loop is to be executed at least once
B. when the loop terminates unexpectedly
C. when the program executes at least once
D. when the number of iterations is known in advance
vii. In which situation a for loop is more appropriate to use?
A. when the body of loop is to be executed at least once
B. when the loop terminates unexpectedly
C. when the program executes at least once
D. when the number of iterations is known in advance
viii. Which of the following transfers control to the beginning of the loop, skipping the
remaining statements?
A. exit function B. continue statement
C. break statement D. nested statement
ix. Which one of the following is valid case statement in switch?
A. case 1: B. case x<4:
C. case ‘ab’: D. case 1.5:
x. One execution of a loop is also known as:
A. cycle B. duration
C. iteration D. test

Answers
i. D ii. B iii. B iv. C v. B
vi. A vii. D viii. B ix. B x. A

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

Short Questions/Answers (Q/A)


1. Why control statements are used in C programs?

Ans: -The statements which are used to control the flow of execution in programs are called control
structures/statements. These are very important in computer programming. They are used to
implement the program logic. The three types of control structures are sequential, conditional and
repetition (iteration).

2. Define different types of control structures.

Ans: -Different types of control structures are defined below.

 Sequential structure: - It refers to execution of instructions one by one in the sequence in


which they appear in the program from top to bottom till the last instruction.
 Conditional structure: - It is also known as decision making structure. It refers to execution
of instructions based on a condition. If a condition is met, a specific set of instructions are
executed otherwise control is transferred to some other part of the program.
 Iteration structure: - It is also known as loop. It refers to execution of same set of
instructions several times unless condition becomes false.

3. Differentiate between if-else and else-if statements.

Ans: - The differences between if-else and else-if statements are as follows.

If-else else-if
 if-else statement allows to make  else-if statement allows to make
decision between two alternatives. decision among several alternatives.
 In if-else statement only one  In else-if more than one conditions are
condition is tested. tested.
 It can be used as an alternative of  It can be used as an alternative of
ternary operator. switch statement.
 Example:  Example:
n = 5: a = 5:
if (n >= o) b = 10;
cout <<”Number is positive”; if (a > b)
else cout <<” a is larger”;
cout <<”Number is negative”; else if (a < b)
cout <<” b is larger”;
else
cout <<” a and b equal”;

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

4. Differentiate between else-if statements and switch statements.

Ans: - The differences between else-if and switch statements are as follows.

else-if switch
 else-if uses multiple decision  switch uses single expression for
statements for multiple choices. multiple choices.
 else-if tests for equality as well as  Switch statement tests only for
for logical expression. equality.
 else-if evaluates integer, character  switch statement evaluates only
or logical type expressions. character or integer value.
 In else-if either if statement will be  switch statement execute one case
executed or else statement is after another till the break statement
executed. is appeared or the end of switch
statement is reached.
 If the condition inside if is false  If the condition inside switch
then by default the else is statement does not match with any of
executed. the case, for that instance the default
statement is executed.
 Example:  Example:
a = 5: cout<<”\n Enter your choice (1-2) = “:
b = 10; cin>>n;
if (a > b) switch (n)
cout <<” a is larger”; {
else if (a < b) case 1:
cout <<” b is larger”; cout “ \n You r in case-1”;
else break;
cout <<” a and b equal”; case 2:
cout “ \n You r in case-2”;
break;
default: cout <<” invalid choice”;
}

5. What is nested if statement?

Ans: - if statement within another if statement is known as nested if statement. The C ++ allows to
nest if, if-else or else-if inside another if, if-else or else-if statement. In nested structure, the control
enters into the inner if only when the outer condition is true. It has the following general syntax:

if (condition) Outer if
if (condition) inner if
{
Statement (s);
{

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

else
{
Statement (s);
}
else
{
Statement (s);
}

6. Differentiate between for and while loop.

Ans: - The differences between for and while loops are as follows.

for loop while loop


 The use of for loop is more  The use of while loop is more
appropriate when the number of appropriate when the number of
repetitions of loop is known in repetitions of loop is not known in
advance. advance.
 The loop variable in for loop is  The loop variable in while loop can
always of numeric data type. also be other than numeric data type.
 Example:  Example:
int n ; int n ;
for ( n = 1 ; n < = 5 ; n ++ ) n=1;
cout << n << endl ; while (n < = 5 )
{
cout << n << endl ;
n ++ ;
}

7. Differentiate between while and do-while loop.

Ans: - The differences between while and do-while loops are as follows.

while loop do-while loop


 while loop is pre-tested loop as the  do-while loop is post-tested loop as
condition is checked in the start. the condition is checked in the end.
 The body statements never  The body statements executes at least
executes if the condition is false at once even if the condition is false.
the beginning.
 There is no semicolon at the end of  There is semicolon at the end of while
while statement. statement.
 Example:  Example:
int n ; int n ;

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

n = 10 ; n = 10 ;
while (n < = 5 ) do
{ {
cout << n << endl ; cout << n << endl ;
n ++ ; n ++ ;
} }
while (n < = 5 );

8. What is the usage of break and continue statements in C programs?

Ans: - break statement: - A break statement has two uses.

 It is used to terminate a case in switch statement and program execution continues from
next statement following the switch statement.
 It is also used to terminate a loop when it is encountered inside a loop and program
execution continues from the next statement following the loop.

continue statement: - The continue statement is used inside a loop. When it is encountered it
transfers control to the beginning of the loop skipping the remaining statements.

9. Write a program that prints all positive numbers less than 15, skipping those that are greater
than 5 and less than 10. (Example of continue statement Page No. 88)

Ans: -

# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
int n
for (n = 1 ; n < 15; n ++)
{
if ((n > 5) && (n < 10))
continue;
cout<< n << “ “;
}
getche ( );
}

Output:-

1 2 3 4 5 10 11 12 13 14 15

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

10. What is the purpose of exit function? Explain with the help of an example.

Ans: - The exit ( ) function is used to terminate a C++ program before its normal termination and
exit to the Operating system. It requires the standard library header file iostream.h. Its general
syntax is:

exit (value);

Here, value is any integer value/variable and is called exit code.

exit (o) ; exits a program without any error.

exit (1) ; indicates that an error must have occurred which helps the programmer to debug
the program.

Example:

cout<<” enter an integer = “;


cin>> n ;
If (n > 0)
cout<<” You entered “ <<n ;
else
exit (0);

11. What is nested loop? Give one example.

Ans: - A loop inside another loop is called nested loop. The C ++ language allows to nest a for, while
or do-while loop inside another for, while or do-while loop. Nested loops are used to print output in
the form of rows and columns like manipulation of two dimensional arrays.
Example: - The following program demonstrates the use of nested loop.
# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
int i, j ;
Output:-
for ( i = 1 ; i < = 5 ; i ++ ) // outer loop
*
{
**
for ( j = 1 ; j < = i ; j ++ ) // inner loop
***
cout<<“ *”;
****
cout <<” \n”;
*****
}
getche ( );
}

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

12. Write the nested loops that will print the following patterns.
a) 1 2 3 4 5 b) 1 2 3 4 5
1 2 3 4 2 3 4 5
1 2 3 3 4 5
1 2 4 5
1 5
Ans: -
b) a)
# include <iostream.h> # include <iostream.h>
# include <conio.h> # include <conio.h>
void main (void) void main (void)
{ {
clrscr ( ); clrscr ( );
int i, j ; int i, j ;
for ( i = 5 ; i > = 1 ; i - - ) for ( i = 1 ; i < = 5 ; i ++ )
{ {
for ( j = 1 ; j < = i ; j ++ ) for ( j = i ; j < = 5 ; j ++ )

cout<< j <<“ \t ”; cout<< j <<“ \t ”;


cout <<” \n”; cout <<” \n”;
} }
getche ( ); getche ( );
} }

13. Write the following code using while loop.

sum = 0;
for ( k = 20 ; k<20 ; k = k + 2)
sum = sum + k;
cout<<”\n Sum = ”<<sum;
Ans: -

sum = 0;
k = 1;
while (k<20)
{
sum = sum + k;
k = k + 2;
}
cout<<”\n Sum = ”<<sum;

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

14. Write the following code using switch statement to produce the same result.
if(choice == 1)
cout<<”\n Sum = “<< x + y;
else if(choice == 2)
cout<<”\n Product = “<< x * y;
else
cout<<”\n Average = “<< (x + y)/2;
Ans: -
switch (choice)
{
case 1: cout<<”\n Sum = “<< x + y;
break;
case 2: cout<<”\n Product = “<< x * y;
break;
default: cout<<”\n Average = “<< (x + y)/2;
}
15. Write the following code using ternary operator to produce the same result.
a = 10;
b = 20;
if(a > b)
k = a + b;
else
k = a – b;
cout<<” result = “<< k;
Ans: -
a = 10;
b = 20;
k = a >b ? a + b : a – b;
cout<<” result = “<< k;

16. What will be the output of the following code?


int k, sum ;
k = 1 ; sum = 0;
while (k <10)
{ sum = sum + k;
cout<<k<<sum;

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

k = k + 2;
}
Ans: -

1 1
3 4
5 9
7 16
9 25
17. What will be the output of the following code?

int a, b, c ;
a = 0; b = 1; c = 2;
a = b + c;
b = ++ a;
c = b ++;
cout<<a<<b<<c;
Ans: -

454

18. Write a program that prints grade based on the marks obtained according to the given
scheme. (Page No.75-76)
Marks Grade

80 ≤ Marks ≤ 100 „A‟


70 ≤ Marks ≤ 79 „B‟
60 ≤ Marks ≤ 69 „C‟
50 ≤ Marks ≤ 59 „D‟
0 ≤ Marks ≤ 49 „F‟
Ans: -

# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
int m ;
char g ;
cout<<” \n Enter Marks (Max 100) = “;
cin>> m ;

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

if (m>= 80)
g = „A‟;
else if (m >= 70)
g = „B‟;
else if (m >= 60)
g = „C‟;
else if (m >= 50)
g = „D‟;
else
g = „F‟;
cout<<“ \n Your grade is “<<g;
getche ( );
}

Output:-

Enter marks (Max 100) = 67


Your grade is C

19. Write a program that that prompts the user to enter a lower-case letter and determines
whether it is vowel and consonant. (Page No.78)

Ans: -

# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
char ch ;
cout<<” \n Enter a lower-case letter : “;
cin>>ch ;
switch (ch)
{
case „a‟:
case „e‟:
case „i‟:
case „o‟:
case „u‟: cout <<”\n You entered a vowel”;
break;

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

default: cout <<”\n You entered a consonant”;


}
getche ( );
}

Output:-

Enter a lower-case letter : b


You entered a consonant

20. Write a program that that prompts the user to enter an upper-case letter and determines
whether it is vowel and consonant.

Ans: -

# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
char ch ;
cout<<” \n Enter an upper-case letter : “;
cin>>ch ;
switch (ch)
{
case „A‟:
case „E‟:
case „I‟:
case „O‟:
case „U‟: cout <<”\n You entered a vowel”;
break;
default: cout <<”\n You entered a consonant”;
} Output:-
getche ( );
Enter an upper-case letter : U
}
You entered a vowel

21. Write a program that that prompts the user to enter a lower-case or upper letter and
determines whether it is vowel and consonant.

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

Ans: -

# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
char ch ;
cout<<” \n Enter a lower-case or an upper-case letter : “;
cin>>ch ;
switch (ch)
{
case „a‟:
case „e‟:
case „i‟:
case „o‟:
case „u‟:
case „A‟:
case „E‟:
case „I‟:
case „O‟:
case „U: cout <<”\n You entered a vowel”;
break;
default: cout <<”\n You entered a consonant”;
}
getche ( );
}

Output:-

Enter a lower-case or an upper-case letter : z


You entered a consonant

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

22. Write a program that prints numbers from 1 to 10 in ascending order.

Ans: -

using for loop using while loop using do-while loop Output: -
# include <iostream.h> # include <iostream.h> # include <iostream.h> 1

# include <conio.h> # include <conio.h> # include <conio.h> 2


void main (void) void main (void) void main (void) 3
{ { {
4
clrscr ( ); clrscr ( ); clrscr ( );
5
int n ; int n ; int n ;
for (n = 1 ; n <=10 ; n ++) n = 1; n = 1; 6
cout<< n <<endl ; while (n <=10) do 7
getch ( ); { { 8
} cout<< n <<endl ; cout<< n <<endl ;
9
n ++; n ++;
10
} }
getch ( ); while (n <=10);
} getch ( );
}

23. Write a program that prints numbers from 1 to 10 in descending order.

Ans: -
using for loop using while loop using do-while loop Output:-
# include <iostream.h> # include <iostream.h> # include <iostream.h> 10
# include <conio.h> # include <conio.h> # include <conio.h>
9
void main (void) void main (void) void main (void)
8
{ { {
clrscr ( ); clrscr ( ); clrscr ( ); 7

int n ; int n ; int n ; 6


for (n = 10 ; n >=1 ; n - -) n = 10; n = 10; 5
cout<< n <<endl ; while (n >=1) do 4
getch ( ); { {
3
} cout<< n <<endl ; cout<< n <<endl ;
2
n - -; n - -;
1
} }
getch ( ); while (n >=1);
} getch ( );
}

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

24. Write a program that prints odd numbers in the range of 1 and 20.

Ans: -

using for loop using while loop using do-while loop Output: -
# include <iostream.h> # include <iostream.h> # include <iostream.h> 1

# include <conio.h> # include <conio.h> # include <conio.h> 3


void main (void) void main (void) void main (void) 5
{ { {
7
clrscr ( ); clrscr ( ); clrscr ( );
9
int n ; int n ; int n ;
for (n = 1 ; n <=20 ; n+=2) n = 1; n = 1; 11
cout<< n <<endl ; while (n <=20) do 13
getch ( ); { { 15
} cout<< n <<endl ; cout<< n <<endl ;
17
n +=2; n +=2;
19
} }
getch ( ); while (n <=20);
} getch ( );
}

25. Write a program that prints even numbers in the range of 1 and 20.

Ans: -
using for loop using while loop using do-while loop Output: -
# include <iostream.h> # include <iostream.h> # include <iostream.h> 2

# include <conio.h> # include <conio.h> # include <conio.h> 4


void main (void) void main (void) void main (void) 6
{ { {
8
clrscr ( ); clrscr ( ); clrscr ( );
10
int n ; int n ; int n ;
for (n = 2 ; n <=20 ; n+=2) n = 2; n = 2; 12
cout<< n <<endl ; while (n <=20) do 14
getch ( ); { { 16
} cout<< n <<endl ; cout<< n <<endl ;
18
n +=2; n +=2;
20
} }
getch ( ); while (n <=20);
} getch ( );
}

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

Long Questions/Answers

1. What is decision control structure? Explain all types of if statements with syntax and
examples.

Ans: - Decision control structures: - Decision control structures are used in programming to make
decisions. They allow programs to execute a specific statement or set of statements based on one or
more conditions.

In C ++ the following decision control structure are available.

a) If statement
b) if-else statement
c) else-if statement
d) switch statement

a) If statement: - if statement is simplest form of a decision control structure. It is used to


execute or skip a block of statements based on a condition.

It has the following general syntax.

If (condition)
{
Block of statements;
)
Explanation:-

 If is a reserved word.
 The condition in if is evaluated.
 If the condition is true, the block of statements given below the condition within the braces
will be executed.
 If the condition is false, the block of statements given below the condition within braces will
be skipped.
 If a single statement is to be executed then braces are not required.

Example: -The following program will print the message “Passed” if marks are more than or equal to
33.

# include <iostream.h>
# include <conio.h>
void main (void)
Output:-
{
clrscr ( ); Enter marks = 50

int marks; Passed

cout<<” \n Enter marks = “;


cin>> marks;

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

if (marks >= 33)


cout<<”\n Passed “;
getch ( );
}
b) If-else statement: - if-else statement is used to make a decision from two alternatives based
on a condition. It is used to execute one block of statements if condition is true and other when
condition is false. In any situation, one block of statements is executed and the other is skipped.

It has the following general syntax.

If (condition)
{
Block of statements-1;
)
else
{
Block of statements-2;
)
Explanation:-

 If and else are reserved words.


 The condition in if is evaluated.
 If the condition is true, the block of statements-1 will be executed and block of statements-2
will be skipped.
 If the condition is false, the block of statements-1 will be skipped and block of statements-2
will be executed.
 In case of single statement is to be executed in both blocks, there is no need to use braces
whether the condition is true or false.

Example: -The following programs will print whether the entered number is even or odd.

# include <iostream.h>
# include <conio.h> Output:-
void main (void)
Enter an integer = 18
{
18 is Even number
clrscr ( );
int n, r ;
cout<<” \n Enter an integer = “;
cin>>n ;
r = n % 2;
if (r == 0)

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

cout<< n <<” is Even number “;


else
cout<< n <<” is Odd number “;
getch ( );
}
c) else-if statement: - else-if statement is used to take a decision from several alternatives
based on more than one conditions. It is used to select one block of statements from available more
than two blocks of statements.

It has the following general syntax.

If (condition-1)

Block of statements-1;

else If (condition-2)

Block of statements-2;

else

Block of statements-n;

Explanation:-

 If and else are reserved words.


 The condition-1 is evaluated.
 If it is true, the block of statements-1 will be executed and all others conditions and block of
statements will be skipped.
 If the condition-1 is false, then condition-2 is evaluated. If it is true then the block of
statements-2 will be executed and all others conditions and block of statements will be
skipped.
 In this manner all conditions are evaluated one by one. If none of the conditions is true then
the block of statements-n in the last else will be executed

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

 If a single statement is to be executed in each block then braces are not required.

Example: -The following programs will print whether the entered number is positive, negative or
equal to zero.

# include <iostream.h>
# include <conio.h> Output:-
void main (void)
Enter an integer = 0
{
0 is equal to Zero
clrscr ( );
int n ;
cout<<” \n Enter a number = “;
cin>> n ;
if (n > 0)
cout<< n <<” is Positive number “;
else if (n < 0)
cout<< n <<” is Negative number “;
else
cout<< n <<” is equal to Zero “;
getch ( );
}

2. Explain the purpose of switch statement with syntax and one example.

Ans: - The switch statement is a control statement that is used when a single block of statements is
to be executed among many choices. It is very similar to else-if structure.

The following is general syntax of switch statement.

switch (constant / variable / expression)

case constant-1: statement (s);


break;
case constant-2: statement (s);
break;
.

default: statement (s);

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

break;
)

Explanation:-

 Switch, case, break and default are reserved words.


 The constant/variable/expression in switch is evaluated.
 The value of constant/variable or result of expression is compared in sequences with the
constant values given after the keyword case.
 If the value/result matches any constant value then the statement(s) following that case
is/are executed. The break statement in that case transfers the control to the first statement
following the end of switch statement.
 If the value/result does not match to none of the constant value given in any case, then
statement(s) given in keyword default is/are executed. The use of default is optional.
 The use of break statement in every case statement causes to exit from the body of switch
statement.

Example: -The following programs will print the name of the week day based on the value of day.

# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
int a ; Output:-

cout<<” \n Enter an integer (1-7) = “; Enter an integer (1-7) = 5


cin>>a ; Friday
switch (a)
{
case 1: cout <<”\n Monday”;
break;
case 2: cout <<”\n Tuesday”;
break;
case 3: cout <<”\n Wednesday”;
break;
case 4: cout <<”\n Thursday”;
break;
case 5: cout <<”\n Friday”;
break;
case 6: cout <<”\n Saturday”;
break;
case 7: cout <<”\n Sunday”;

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

break;
default: cout <<”\n Not a valid day”;
}
getch ( );
}
3. What is looping structure? Explain all types of looping statements with syntax and examples.

Ans: - Loop: - A loop is a control structure that repeatedly executes a statement or block of
statements as long as the condition remains true. Loops are also called iteration or repetition
structures.

There are three types of loops in C++.

a) for loop b) while loop c) do-while loop

a) for loop: - A for loop is used to execute one or more statements for a specific number of times. It
is also called determined or counter loop. This loop is more suitable in situations where the
number of repetitions is known in advance. It has the following general syntax.

for (initialization ; condition ; increment/decrement)


{
Block of statements;
)
Explanation:-

 for is a reserved word.


 A variable known as loop counter or loop variable is assigned an initial value in the
initialization part of the loop.
 The condition is evaluated. If the condition is true, the block of statements within the braces
is executed.
 After the execution of statements, control is transferred to the increment/decrement part of
the loop. Here the value of the variable is incremented or decremented.
 The condition is again evaluated. If it is true the body of loop is executed again. If the
condition becomes false, the loop terminates and control is transferred to the next
statement after the block of statements.
 If only a single statement is to be executed then braces are not required.

Example: -The following programs will print the numbers from 1 to 5 in ascending order.

# include <iostream.h> Output:-


# include <conio.h> 1
void main (void)
2
{
3
clrscr ( );
4
int n ;
5

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

for (n = 1 ; n <=5 ; n ++)


cout<< n <<endl ;
getch ( );
}
b) while loop: - A while loop is sentinel loop statement. In this loop the condition is checked at the
beginning of the loop. The body of loop executes as long as condition remains true. The control
can exit from while loop when either condition becomes false or break statement is used.
It has the following general syntax.

while
{
Block of statements;
)
Explanation:-

 while is a reserved word.


 The condition is evaluated.
 If the condition is true, the block of statements within the braces is executed.
 After the execution of statements, control is transferred back to the beginning of the loop.
 The condition is again evaluated. If it is true the body of loop is executed again. If the
condition becomes false, the loop terminates and control is transferred to the next
statement after the block of statements.
 If the body of loop consists of a single statement then braces are not required.

Example: -The following programs will print the numbers from 1 to 5 in ascending order.

# include <iostream.h>
# include <conio.h> Output:-
void main (void)
1
{
2
clrscr ( );
int n ; 3

n = 1; 4
while ( n <=5 ) 5
{
cout<< n <<endl ;
n ++ ;
}
getch ( );
}

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

c) do-while loop: - In do-while loop the condition is checked at the end of the loop due to which
body of the loop is executed at least once. The body of loop executes as long as condition
remains true. In this type of loop the control can exit from loop when either condition becomes
false or break statement is used. The general syntax of do-while loop is:

do
{
Block of statements;
)
while (condition);
Explanation:-

 do and while are reserved words.


 After executing the block of statements, the condition at the end is evaluated.
 If the condition is true, the control is transferred back to the beginning of the loop.
 The loop is executed once again and then the condition is checked again. The process
continues till the condition becomes false.
 When the condition becomes false. Control is transferred to the next statement after the
keyword while.
 If the body of loop consists of a single statement then braces are not required.

Example: -The following programs will print the numbers from 1 to 5 in ascending order.

# include <iostream.h>
# include <conio.h> Output:-
void main (void)
1
{
2
clrscr ( );
int n ; 3

n = 1; 4
do 5
{
cout<< n <<endl ;
n ++ ;
}
while ( n <=5 )

getch ( );
}

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

Lab Activities
1. Write a program that reads a number and prints its square if the number is greater than 10
otherwise its cube.

Ans: -

# include <iostream.h>
# include <conio.h> Output:-
void main (void)
Enter a number = 7
{
Cube = 343
clrscr ( );
int n ;
cout<<” Enter a number = “;
cin>>n ;
if (n > 10)
cout<<” \n Square = “<< n * n;
else
cout<<” \n Cube = “<< n * n *n;

getch ( );
}
2. Write a program that reads an integer and prints whether it is odd or even number.

Ans: - # include <iostream.h>

# include <conio.h> Output:-


void main (void) Enter an integer = 35
{ 35 is Odd number
clrscr ( );
int n, r ;
cout<<” \n Enter an integer = “;
cin>> n ;
r = n % 2;
if (r == 0)
cout<< n <<” is Even number “;
else
cout<< n <<” is Odd number “;
getch ( );
}

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

3. Write a program that reads three numbers and prints the largest one.

Ans: -

# include <iostream.h>

# include <conio.h>
void main (void)
{
clrscr ( );
int a, b, c ;
cout<<” \n Enter first number = “;
cin>>a ;
cout<<” \n Enter second number = “;
cin>>b ;
cout<<” \n Enter third number = “;
cin>>c ;
if ( (a > b) && (a > c))
cout <<”\n Largest number is ”<< a;
else if (b > c)
cout<<”\n Largest number is “<< b;
else
cout<<”\n Largest number is “<< c;
getch ( );
}

Output:-

Enter first number = 20


Enter second number = 45
Enter third number = 60
Largest number is 60

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

4. Write a program that reads a letter and prints whether it is a lower-case or upper-case letter.

Ans: -
# include <iostream.h>
# include <conio.h>
void main (void) Output:-
{
Enter a lower-case or an upper-case letter : Z
clrscr ( );
Z is an upper-case letter
char ch ;
cout<<” \n Enter a lower-case or an upper-case letter : “;
cin>>ch ;
if ( (ch>= „a‟) && (ch<= „z‟) )
cout <<ch<<” is a lower-case letter”;
else if ( (ch>= „A‟) && (ch<= „Z‟) )
cout <<ch<<” is an upper-case letter”;
else
cout <<”\n Alphabet was not entered”;
getch ( );
}

5. Write a program that reads an integer and prints its multiplicative table upto 20.

Ans: -
# include <iostream.h>
# include <conio.h> Output:-
void main (void) Enter an integer = 5
{
Table of 5
clrscr ( );
-----------------------
int n, i ;
cout<<”\n Enter an integer = “; 1x5=5

cin>>n ; 2 x 5 = 10
cout<<”\n Table of “<< n ; 3 x 5 = 15
cout<<”\n -----------------------“;
4 x 5 = 20
for (i = 1 ; i<=20 ; i++)
.
cout<<i<< “ x “<< n <<” = “<< i * n <<endl ;
getch ( ); .

} 20 x 5 = 100

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

6. Write a program to calculate the basic pay of an employee using the given formula.
Net Pay = Basic Pay + House Rent
House Rent is based on the basic pay according to the scheme given below.
Basic Pay House Rent
Basic Pay 30000 30 % of Basic pay
Basic Pay ≥ 30000 and ≤ 50000 35 % of basic pay
Basic Pay > 50000 40 % of basic Pay
Ans: -
# include <iostream.h>
Output:-
# include <conio.h>
void main (void) Enter Basic Pay of Sameer = 80000

{ Net Pay of Sameer =112000


clrscr ( );
int b_pay, h_rent, net_pay;
cout<<”\n Enter Basic Pay of Sameer = “;
cin>>b_pay ;
if (b_pay < 30000)
h_rent = 30.0/100 * b_pay;
else if ( (b_pay >= 30000) && (b_pay <=50000) )
h_rent = 35.0/100 * b_pay;
else
h_rent = 40.0/100 * b_pay;
net_pay = b_pay + h_rent;
cout<<”\n Net Pay of Sameer= “<< net_pay;
getch ( );
}

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

7. Write a program that will produce a table of equivalent temperatures in both Fahrenheit and
Celsius with an increment of 5 from 50 to 100 as given below:
C = 5/9 (F – 32)
Fahrenheit Celsius
50 9.90
55 12.65
.
.
.
100 37.4

Ans: -
# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
int f ;
float c ;
cout” Fahrenheit \t Celsius”;
for ( f = 50 ; f <= 100 ; f +=5)
{
c = 5.0/9 * (f – 32);
cout<< f << ”\t“<<c <<endl;
}
getch ( );
}

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

8. Write a program that prints the sum of the following sequence using for loop.
sum = 30 + 33 + 36 + 39 + . . . + 60

Ans: -
# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
int i, sum ;
sum = 0 ;
for ( i = 30 ; i<= 60 ; i +=3)
sum = sum + i ;
cout<<“Sum = “<<sum ;
}
getch ( );
}

9. Write a program that prints the sum of the following sequence using while loop.
sum = 30 + 33 + 36 + 39 + . . . + 60

Ans: -
# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
int i, sum ;
sum = 0 ;
i = 30 ;
while (i <= 60)
{
sum = sum + i ;
i +=3;
}
cout<< “Sum = “<< sum ;
}
getch ( );
}

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

10.Write a program that prints all positive odd numbers upto 50 skipping those that are divisible
by 5 using continue statement.

Ans: -
# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
int n, r ;
for (n = 1 ; n < 50; n +=2)
{
r = n % 5;
if (r == 0)
continue;
cout<< n << “ “;
}
Output:-
getche ( );
1 3 7 9 11 13 17 19 21 23 27 29 31 33 37 39 41 43 47 49
}

11.Write a program that reads an integer and prints its factorial.


Ans: -
# include <iostream.h>
# include <conio.h>
void main (void)
{
clrscr ( );
int n, i, fact ;
fact = 1 ;
cout<<” Enter a positive integer = “;
cin>> n ;
for (i = 1 ; i<=n; i++)
fact = fact * i ;
cout<<“\n Factorial of << n << “ = “<< fact ;
} Output:-
getche ( );
Enter a positive integer = 6
}
Factorial of 6 = 720

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

12.Write a program that reads the coefficients a, b and c of the quadratic equation ax2 + bx + c = 0

and prints the real solutions of x, using the formula.
Note that if b2 – 4ac = 0 then there is only one real solution. If it is greater than zero then
there are two real solutions and if it is less than zero then print the message “No Real
Solutions”.

Ans: - # include <iostream.h>


# include <conio.h>
# include <math.h>
void main (void)
{
clrscr ( );
float a, b, c, x1, x2, d;
cout<<” \n Enter first coefficient = “;
cin>>a ;
cout<<” \n Enter second coefficient = “;
cin>> b ;
cout<<” \n Enter third coefficient = “;
cin>> c ;
d = b * b – 4 * a * c;
if (d ==0)
{
cout<<” \n One Real Solution “;
x1 = ( - b + sqrt (d) )/2.0 * a ;
cout<<” \n x1 = x2 = “ << x1;
}
else if (d >0)
{
x1 = ( - b + sqrt (d) )/ 2.0 * a ; Output:-
x2 = ( - b - sqrt (d) )/ 2.0 * a ; Enter first coefficient = 3
cout<<” \n Two Real solutions “;
Enter second coefficient = 5
cout<<” \n x1 = “ << x1 ;
Enter third coefficient = 3
cout<<” \n x2 = “ << x2 ;
} No Real Solutions

else
cout<< “\n No Real Solutions” ;
getche ( );
}

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

You might also like