0% found this document useful (0 votes)
63 views

Labsheet 5

The document discusses various iterative/loop constructs in computer programming including for, while, and do-while loops. It provides examples of using each loop type and explains the differences between entry-controlled loops like for and while versus exit-controlled loops like do-while. Key aspects like initialization, condition checking, updating loop variables, and using break/continue statements are described.

Uploaded by

saurabharpit
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)
63 views

Labsheet 5

The document discusses various iterative/loop constructs in computer programming including for, while, and do-while loops. It provides examples of using each loop type and explains the differences between entry-controlled loops like for and while versus exit-controlled loops like do-while. Key aspects like initialization, condition checking, updating loop variables, and using break/continue statements are described.

Uploaded by

saurabharpit
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/ 15

Birla Institute of Technology and Science - Pilani,

K.K.Birla Goa Campus


Computer Programming (CSF 111)
Second Semester 2015-16
Lab Sheet - 5: Iterative/Looping Constructs

Objectives
1. for loop
2. while loop
3. do-while loop
4. break/continue in loops
5. Nested loops

Iterative/Loop Constructs
Iterative constructs are used to execute a block/single line of code for a specied number
of times or until a condition is satised. Iterative constructs declaration and execution can
be done in the following way,
1. declare one or more variables to be used for condition check
2. check condition to start loop
3. execute conditions inside loop
4. change value of variables to be used for condition check
The execution of a loop depends upon satisfaction of a condition. If the loop condition
yields non zero value(negative and positive values), the loop would continue to execute,
otherwise the execution control would be transferred to the next line after the loop block1 .
Iterative constructs are classied as:

Entry controlled loop


Test condition is checked before execution of the loop block.Ex:

 for
 while
1 The

part of code that would execute until loop condition satised is referred to as loop block here

Figure 1: Flowchart of an entry con- Figure 2: Flowchart of an exit controlled loop


trolled loop

Figure 1 shows the owchart of entry loop.

Exit controlled loop


Loop block is executed rst and then the condition is checked to decide for further
execution. Hence loop block is guaranteed to execute atleast once. Ex:

 do-while
Figure 2 shows the owchart of exit controlled loop.

The "for" loop

for is an entry controlled iterative construct. First initialization is done and then condition is checked. If condition yields non zero(True) value then loop block is executed. after

completion of execution of loop block, values of variables used in condition are changed and
then condition is rechecked for next iteration. This continues until the condition yields 0
(False).

Structure of for loop


for loop has the following structure:

for(initialization;test-condition;Update of variables used in condition)


{
loop_body
}
for loop continues to execute as long as test-condition continues to evaluate to non zero.
Loop structure mainly has 3 parts,
1. Initialization
2. Conditional Testing
3. Update of loop control variable
All of them are optional.
Note : If loop body is not written in {} then the statement next to for statement is only
executed as loop block.

Example 1 :Program to print Hello World 10 times


#i n c l u d e <s t d i o . h>
v o i d main ( ) {
int i ;
f o r ( i =0; i <10; i ++){
p r i n t f ( " H e l l o World\n " ) ;
}
}

The same program can also be written as


#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t i =0;
f o r ( ; i <10; i ++){
p r i n t f ( " H e l l o World\n " ) ;
}
}

and also as
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t i =0;
f o r ( ; i <10;){
p r i n t f ( " H e l l o World\n " ) ;
i ++;
}
}

or simply
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t i =0;
for (;;){
p r i n t f ( " H e l l o World\n " ) ;
i ++;
i f ( i >=10)
break ;
}
}
As already explained, the 3 parts of the for loop are optional.
In the last code, the initialization was done right before for statement. Then the value was
updated at i++. Then the condition check was done at if (i >= 10) statement. If the 'if
condition' is satised, break statement will take the control out of the for construct.
Answer to yourself: what would the following program do?
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
for (;;){
p r i n t f ( " H e l l o World\n " ) ;
}
}

The "while" loop

while construct is also an entry-controlled looping structure like for. If the condition
evaluates to non zero then loop block is executed, otherwise control jumps out of the while
loop to the next statement after the while block.

structure of while loop


w h i l e ( t e s t c o n d i t i o n )
{
statement ( s ) ;
}
The update of loop variables may(or may not) be done in loop block.

Example 2 :Program to print Hello World 10 times

A program to print table of a number after receiving number as input from the user
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t num , i =1;
p r i n t f ( " Enter a number : " ) ;
s c a n f ("%d",&num ) ;
w h i l e ( i <=10){
p r i n t f ("%d %d = %d\n" ,num , i , i num ) ;
num=num+1;
}
}

Example 3 :Write a program to nd factorial of a number using for


loop
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t n , i , f a c =1;
s c a n f ("%d",&n ) ;
i =2;
w h i l e ( i<=n ) {
f a c=f a c i ;
i ++;
}
p r i n t f ("%d!=%d\n " , n , f a c ) ;
}

Do It Yourself : Write the same program as above using while loop


Example 4 : Program to print oor(logn(x)) of numbers n and x taken
from user
Take a number n and another number x from user and nd oor(logn (x)),provided that
n<=x

#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t n , x , i , j =0;
p r i n t f ( " Enter n , x : " ) ;
s c a n f ("%d%d",&n,&x ) ;
i=x ;
w h i l e ( i >1){
i=i /n ;
j ++;
}
p r i n t f ( " c e i l ( log_%d(%d))=%d\n " , n , x , j ) ;
}

Do It Yourself :Write the same program as above using for loop

The "do-while" loop

do-while is an exit controlled iterative construct unlike for and while. Here the body of
the loop is executed rst and then the condition is checked. If the condition evaluates to
non zero then the loop body execution is continued otherwise it stops executing loop body.
Thus this loop is executed at least once without considering the condition. Refer to Figure
2 for a owchart.

Structure of do-while
// d e c l a r a t i o n
do{
// s t a t e m e n t ( s )
} while ( condition ) ;
Here the loop block is executed rst of all after which condition in the while bracket
is checked. If that condition is satised then the statements of loop block are re-executed,
otherwise the control is transferred to rst statement after the while statement of do-while
loop.

Example 5 :Program to Accept a number from user and tell whether


it is odd or even and continue this till user enters y as choice
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
int n;
c h a r ch ,dm;
do{
p r i n t f ( " Enter a number : " ) ;
s c a n f ("%d",&n ) ;

i f ( n%2)
else

p r i n t f ( " odd\n " ) ;

p r i n t f ( " even \n " ) ;


p r i n t f ( " y/n : " ) ;
s c a n f ("%c%c ",&dm,& ch ) ;
} w h i l e ( ch=='y ' ) ;

Note : The char variable dm in the above program is a variable used to store the newline
entered by the user after inputting n. Otherwise, that newline would go into ch variable and
loop would exit at once. Try the code by removing variable dm yourself.

When to use while construct and when to use do-while construct


Whenever the execution of code inside loop-block is to be done atleast once, then dowhile loop is used. For example in Example 7, the choice of the user was not known until
the rst output of odd even was made. Hence do-while loop was optimal in this case. The
same program would be written as follows if while loop was used.
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
int n;
c h a r ch ='y ' ,dm;
w h i l e ( ch=='y ' ) {
p r i n t f ( " Enter a number : " ) ;
s c a n f ("%d",&n ) ;
i f ( n%2)
p r i n t f ( " odd\n " ) ;
else
p r i n t f ( " even \n " ) ;
p r i n t f ( " y/n : " ) ;
s c a n f ("%c%c ",&dm,& ch ) ;
}
}
As clearly visible, using while loop for Example 7 caused an unnecessary initialization of
ch='y'.

Can You write Examples 2,3 and 5 using do-while loop?

Innite loop
while (1){
// s t a t e m e n t ( s )
}
or
for (;;){
// s t a t e m e n t ( s )
}
or
do{
// s t a t e m e n t ( s )
} while ( 1 ) ;
All the loops above will run innitely. How to control such loops? The answer lies in break
statement.

The "break/continue" statements in loops

The "break" statement


break statement stops further execution of the loop and transfers the control to statement after the loop block ends.If there are more statements after break in the block, those
statements will not be executed and the control would go out of the current loop in which
break statement was used.

How to use break?


We may use an if condition inside a loop, on satisfaction of which we can to terminate
the loop.
Ex:
i =0;
while (1){
i ++;
i f ( i ==100)
break ;
}
or
i =0;
for (;;){
i ++;
i f ( i ==100)
break ;
}

or
i =0;
do{

i ++;
i f ( i ==100)
break ;
} while ( 1 ) ;

What would happen if there is no if condition before break i.e. break


can be accessed directly without satisfying any if? Find yourself.
Example 6 : Try the following code and observe the outputs and nd
out what happens when loop stops by break statement and why that
happens.
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
int n;
c h a r ch ='y ' ,dm;
while (1){
p r i n t f ( " Enter a number :
s c a n f ("%d",&n ) ;
i f ( n%2)
p r i n t f ( " odd\n " ) ;
else
p r i n t f ( " even \n " ) ;
p r i n t f ( " y/n : " ) ;
s c a n f ("%c%c ",&dm,& ch ) ;
i f ( ch=='n ' )
break ;
p r i n t f ( " Statement1 a f t e r
p r i n t f ( " Statement2 a f t e r
p r i n t f ( " Statement3 a f t e r
p r i n t f ( " Statement4 a f t e r
p r i n t f ( " Statement5 a f t e r
}
}

");

if
if
if
if
if

with
with
with
with
with

break \n " ) ;
break \n " ) ;
break \n " ) ;
break \n " ) ;
break \n " ) ;

The "continue" statement


continue is used to skip further execution of block in current iteration and move to the
next iteration. If there are statements after the continue block, they will not be executed.
For example, consider a program of printing numbers from 1 to 100 and skip all the divisibles
of 7. It would be very unwise to use 15 loops (1 to 6),(8 to 13), (15 to 20), (22 to 27), (29

to 34), (36 to 41), (43 to 48), (50 to 55), (57 to 62), (64 to 69), (71 to 76), (78 to 83),
(85 to 90),(92 to 97) and (99 to 100). continue statement would facilitate us under such
circumstances when there are certain conditions, on satisfaction of which execution of block
after some point should not be done.

Example 7 : A program to print numbers from 1 to 100 except for


numbers divisible by 7
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
int i ;
f o r ( i =0; i <100; i ++){
i f ( i %7==0){
continue ;
}
p r i n t f ("%d\n " , i ) ;
}
}

Do It Yourself : Repeat Example 7 using while loop


Find Out Yourself : What would happen if a break was written
instead of continue in Example 7?
Example 8 : Take a number n from user and print all numbers from
1 to n specifying whether intermediate numbers are divisible by 3 or
divisible 5 or divisible by both and stop when a number divisible by
3,5 and 7 is found
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t n , i =1;
s c a n f ("%d",&n ) ;
w h i l e ( i++<=n ) {
i f ( ( i 1)%3)
continue ;
i f ( ( i 1)%5)
continue ;
i f ( ( i 1)%3==0&&(i 1)%5==0&&(i 1)%7==0)
break ;
p r i n t f ("%d i s d i v i s i b l e by 3 and 5 but not by 7\n " , i 1);
}
}

Do It Yourself : Write Example 8 using for loop

Nested Loops

Just like 'if' constructs, iterative constructs can also be nested and can be nested upto as
many levels as we want. Nested iterative constructs are quite useful as the coming Examples
will show.

Example 9 : Code to write tables from 1 to n, where n is input by


user.
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
int n , i , j ;
s c a n f ("%d",&n ) ;
f o r ( i =1; i<=n ; i ++){
f o r ( j =1; j <=10; j ++){
p r i n t f ("%d %d = %d\n " , i , j , i j ) ;
}
}
}

Example 10 : Code to print a pattern


1
1 2
1 2 3
1 2 3 4
..
1 2 3 4 ...n
where n i s i n p u t by u s e r .
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t n , i =1, j ;
s c a n f ("%d",&n ) ;
w h i l e ( i<=n ) {
f o r ( j =1; j<=i ; j ++){
p r i n t f ("%d " , i ) ;
}
p r i n t f ("\n " ) ;
i ++;
}
}

Note : we can nest any construct into another dierent construct as well up to any level.
while ( condition1 ){
f o r ( i n i t i a l i z a t i o n ; c o n d i t i o n 2 ; update ) {
do{
while ( condition4 ){
do{
f o r ( i n i t i a l i z a t i o n ; c o n d i t i o n 6 ; update )
// f u r t h e r n e s t i n g

}
} while ( condition5 ) ;

}
} while ( condition3 ) ;

Example 12 : Code to print a pattern

...
1 2 3 4 ...

1
1 2
1 2 3
1 2 3 4
n

where n is input by user.


#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t n , i =1, j ;
s c a n f ("%d",&n ) ;
w h i l e ( i<=n ) {
f o r ( j =1; j <=2(n i ) ; j=j +1){
p r i n t f (" " ) ;
}
f o r ( j =1; j<=i ; j ++){
p r i n t f ("%d " , i ) ;
}
p r i n t f ("\n " ) ;
i ++;
}
}

Try yourself
What will be the outputs of following code snippets(Note the semicolon right after the
"for" and "while" brackets close):
1.
2.

f o r ( i =0; i <10; i ++);


p r i n t f ("%d " , i ) ;
i =0;
w h i l e ( i ++<10);
p r i n t f ("%d " , i ) ;

Write a program to print a 20x20 square on screen2

#i n c l u d e <s t d i o . h>
v o i d main ( ) {
int i , j ;
f o r ( i =0; i <20; i ++){
i f ( i ==0|| i ==19){
f o r ( j =0; j <20; j ++){
p r i n t f ( "_" ) ;
}
p r i n t f ("\n " ) ;
}
e l s e i f ( i !=0&& i !=19){
printf ("|");
f o r ( j =1; j <19; j ++){
p r i n t f (" " ) ;
}
printf ("|\n");
}
}

Exercises
1. Approximate the value of pi using the following series expansion.
pi = 4  4/3 + 4/5  4/7 + . . . + (-1)n-1 4/(2n+1) + . . .
2. Find all prime numbers that are less than 100. Recall that a number is prime only if
the only numbers that evenly divide it are 1 and itself.
3. Write a program to reverse a number i.e. 12345 to 54321

2 Note : the result of code may appear to be rectangle because vertical 1 unit might not be the same as
horizontal 1 unit on screen.

4. Write a program to print the average of rst ten natural numbers.


5. Write a program that prints an average of N integer numbers. Ask the user how many
number he wants to enter? (Using for loop).
6. Write a program that prints the average of N oat numbers. Ask the user how many
number he/she wants to enter. (Using while loop)
7. Write the last program using do-while construct.
8. Write a program that reads an integer and nds the sum of digits of the number.
9. Write a program to convert a decimal number into corresponding binary equivalent.
10. Write a program to compute and output the rst N terms of the Fibonacci series,
whose rst 8 terms are as follows:
0 1 1 2 3 5 8 13.
N will be an input value
Hint: Each term is dependent on two previous terms.
11. Write a program to calculate the sum of the following series up to N terms
3
4
2
x ( x ) + ( x ) ( x ) . . .
(2)

(3)

(4)

N and x will be input values. Use math library for sqrt function. Note that sqrt takes
a double argument and returns a double value. To obtain better precision dene x as a
double and obtain the sum as a double value as well. Also note that the math library
has to be linked explicitly.
12. Write a program to nd the rst N prime numbers.
13. Write a program to print the following pyramid.
0
111
22222
3333333
444444444

Solutions to few Questions

Solution 1
#i n c l u d e <s t d i o . h>
i n t main ( )
{
i n t count , numOfTerms ;
double pi = 0 ;

p r i n t f ( " \ nNumber o f terms ( must be 1 o r l a r g e r ) : " ) ;


s c a n f ("%d",&numOfTerms ) ;
f o r ( count = 1 ; count <= numOfTerms ; count++) {
i f ( count % 2 == 0 )
p i += ( 4 . 0 / ( 2 . 0 count 1) ) // Odd term
else
p i = ( 4 . 0 / ( 2 . 0 count 1) ) // Even term
}
p r i n t f ( " \ n The approximate v a l u e o f p i i s %f " , p i ) ;
}

Solution 3
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t num , r e v e r s e =0,temp ;
s c a n f ("%d",&num ) ;
temp=num ;
w h i l e ( temp !=0){
r e v e r s e=r e v e r s e 10+(temp %10);
temp=temp / 1 0 ;
}
p r i n t f ("%d\n " , r e v e r s e ) ;
}

Solution 9
#i n c l u d e <s t d i o . h>
v o i d main ( ) {
i n t num , b i n a r y =0,temp , i =1;
s c a n f ("%d",&num ) ;
temp=num ;
w h i l e ( temp !=0){
b i n a r y=b i n a r y +(temp%2) i ;
i=i 1 0 ;
temp=temp / 2 ;
}
p r i n t f ("%d\n " , b i n a r y ) ;
}

You might also like