LOOPING
Ø In looping, sequence of statements are executed until some conditions for termination of the loop are satisfied.
Ø A program loop therefore consists of two segments, one known as the body of the loop and the other known as the control statement.
Ø The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.
Ø There are three methods by way of which we can repeat a part of a program.
1. The For Statement.
2. The While Statement
3. The Do-While Statement
THE FOR STATEMENT
Ø The for statement is entry controlled loop and most commonly used looping statement in C.
Ø The general form is
for ( Expression 1; Expression 2; Expression 3)
{
Body of the loop;
}
Ø Where expression 1 is used to initialize some parameter that controls the looping action.
Ø Expression 2 represents a condition, that must be true for the loop to continue execution, and expressions is used to alter the value of the parameter initially assigned by parameter 1. Typically expression 1 is an assignment expression, expression 2 is a logical expression, and expression 3 is a unary or assignment expression.
Example : Printing of 100 Natural Numbers.
main ( )
{
int i;
for ( i = 1; i < = 100 ; i+ +)
{
printf("%d\n", i );
}
}
How the For loop gets executed is :
- When the for statement is executed for the first time, the value of count is set to an initial
value 1.
- Now the condition count < = 3 is tested. Since count is 1, the condition is satisfied and
the body of the loop is executed for the first time.
- Upon reaching the closing brace of for, computer sends the control back to the for
statement, where the value of count gets incremented by 1.
- Again the test is performed to check whether the new value of count exceeds 3.
- The value of count is still within the range of 1 - 3. The statements within the braces of for are executed again.
- The body of for loop continues to get executed till count doesn't exceed the final value 3.
- When count reaches the value 4, the control exits from the loop and is transferred to the statement immediately after the body of for.
Let us now write down the program to print numbers from 1 to 10 in different ways. This time we would use a for loop instead of a while loop.
(a) main ( )
{
int I;
for ( I = 1; I < = 10 ; I + +)
{
printf("%d\n", I );
}
}
Note that the initialization, testing and incrementation of loop counter is done in the for statement it self, instead of I = I + 1, Statements I + + or I + = 1 can also be used.
(b) main ( )
{
int I;
for ( I = 1; I < = 10 ; )
{
printf("%d\n", I );
I + = 1;
}
}
Here the incrementation is done within the body of the for loop and not in the for statement. Note that in spite of this the semicolon after the condition is necessary.
(c) main ( )
{
int I = 1;
for ( ; I < = 10 ; I + +)
{
printf("%d\n", I );
}
}
Here the initialization is done in the declaration statement it self. But still semicolon before the condition is necessary.
(d) main ( )
{
int I = 1;
for ( ; I < = 10 ; )
{
printf("%d\n", I );
I + = 1;
}
}
Here neither the incrementation nor the initialization is done in the for statement but still the two semicolons are necessary.
(e) main ( )
{
int I;
for ( I = 1; I ++ < = 10 ; )
{
printf("%d\n", I );
}
}
Here the incrementation as well as comparison one through the same statement, I++ < 10. since ++ operator comes after I , first comparison is done followed by incrementation.
(f) main ( )
{
int I;
for ( I = 1; + + I < = 100 ; )
{
printf("%d\n", I );
}
}
Here both the comparison and incrementation is done through the same statement , + + I < = 10. since ++ precede I, firstly incrementation is done, followed by comparison.
THE WHILE STATEMENT :
Ø The simplest of all the looping structures in C is the while statement.
Ø The while is an entry controlled loop statement.
Ø The basic format of the while statement is
While (Test Condition)
{
Body of the Loop;
}
Statement-x;
Ø The test condition is evaluated and if the condition is true, then the body of the loop is executed.
Ø After execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again.
Ø This process of repeated execution of the body is continues until the test condition finally becomes false and the control is transferred out of the loop.
Ø On exit, the program continues with the statement, immediately after the body of the loop.
Ø The body of the loop may have one or more statements.
Ø The braces are needed only if the body contains two or more statements.
Ø However it is a good practice to use braces even if the body has only one statement.
Example1 :
int i=1;
while (i < = 10)
{
printf ("%d \t", i);
i++;
}
Output: 1 2 3 4 5 6 7 8 9 10
In the above example, body of the loop is executed 10 times for n =1,2,3,….,10 each time printing the value of 'i', which is incremented inside the loop. The test condition may also be written as i<11. The result would be the same.
As a rule, the while must test a condition, that will eventually became false, otherwise the loop would be executed forever, indefinitely.
Example :
main ( )
{
int I = 1;
while ( I < = 100)
{
printf ("%d\n", I);
}
}
This is an indefinite loop, since I remains equal to 1 forever. The correct form would be as discussed above.
What will be the output of the following program ?
main ( )
{
int I = 1;
while ( I < = 100);
{
printf ("%d\n", I);
}
}
This is another indefinite loop, and it doesn't give any output at all. The reason is, we have carelessly given a ; after the while. This would make the loop work like this.
while (I < = 100)
{
;
}
Since the value of I is not getting incremented the control would keep rotating within the loop, eternally.
There are variety of operators which are frequently used with while to illustrate their usage. Let us consider a problem where in numbers from 1 to 10 are to be printed on the screen. The program for performing this task can be written using while in the following different ways.
(a) main ( )
{
int I = 1;
while ( I < = 10)
{
printf ("%d\n", I);
I = I + 1;
}
}
(b) main ( )
{
int I = 1;
while ( I < = 10)
{
printf ("%d\n", I);
I + +;
}
}
Note that the increment operator ++ increments the value of I by 1. Every time the statement I + + gets executed. Similarly to reduce the value of a variable by 1, decrement operator -- is also available.
(c) main ( )
{
int I = 1;
while ( I < = 10)
{
printf ("%d\n", I);
I + = 1;
}
}
Note that + = is a compound assignment operator. It increments the value of I by 1. Similarly j = j + 10 can also be written as j += 10. Other compound assignment operators are -=, *=, /=, %=.
(d) main ( )
{
int I = 0;
while ( I + + < = 10)
{
printf ("%d\n", I);
}
}
In the statement while (I + + <= 10), first the comparison of value of I with 10 is performed and then the incrementation of I takes place. When the control reaches printf (), I has already been incremented . hence I must be initialized to 0.
(e) main ( )
{
int I = 1;
while ( + + I < = 10)
{
printf ("%d\n", I);
}
}
In the statement while (+ + I < = 10), first incrementation of I takes place then the comparison of I with 10 is performed.
THE DO - WHILE STATEMENT
The while loop construct, that we have discussed in the previous section makes a test of condition before the loop is executed. Therefore the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. On some occasions it might be necessary to execute the body of the loop before test is performed. Such situations can be handled with the help of do - while statement. The general form is
do
{
body of the loop;
}while ( Test Condition);
On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the test condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement.
Since the test condition is evaluated at the bottom of the loop, the do - while construct provides an exit controlled loop and therefore the body of the loop is always executed at least once.
Example that shows difference between while and do - while.
main ( )
{
while ( 4 < 1)
{
printf ( "Hello there\n");
}
}
Here since the condition fails for the first time it self, the printf() will not get executed at all. Let's now write the same program using a do - while loop.
main ( )
{
do
{
printf("Hello There\n");
} while ( 4 < 1);
}
In this program the printf () would be executed once since first the body of the loop is executed and then the condition is tested.
THE BREAK STATEMENT
The break statement is used to terminate loops or to exit from a switch statement. It can be used within a for, while , do - while or switch statement. The break statement is written simply as
Break;
Example : Write a program to determine whether a number is prime or not. A prime number is one which is divisible by 1 or it self.
main ( )
{
int num, I;
printf (" Enter a Number ");
scanf ("%d", &num);
I = 2;
While ( I < num )
{
if (num % I = = 0 )
{
printf ( " Not a Prime ");
break;
}
I + +;
}
if (I = = num)
{
printf("Prime Number");
}
}
In this program, the moment num % I turns out to be zero (i.e. num is exactly divisible by I), the message " Not a Prime " is printed and the control breaks out of the loop.
Why does the program requires the if statement after the while loop at all ? There are two ways the control could have reached out side the while loop.
In the second case, it means that there was no number between 2 and num - 1 that could exactly divide num. That is num is indeed a prime. If this is true, the program should print the message " Prime Number ".
The keyword break breaks the control only from the while in which it is placed .
THE CONTINUE STATEMENT
In some programming situations, we want to take the control to the beginning of the loop, bypassing the statements inside the loop which have not yet been executed. The keyword continue allows us to do this. When the keyword continue is encountered inside any C loop, control automatically passes to the beginning of the loop. A continue is usually associated with an if.
Example :
main ( )
{
int I , j ;
for (I = 1; I < = 2 ; I + + )
{
for( j = 1 ; j < = 2 ; j + + )
{
if ( I = = j)
{
continue;
}
printf ( "%d %d\n", I, j);
}
}
}
Output would be
1 2
2 1
Note that when the value of I equals j, the continue statement takes the control to the inner for loop bypassing the rest of the statements pending execution in the inner for loop.
Q) Smriti wants to make a program to print the sum of square of the first 5 whole numbers (0...4). She writes the following program:
integer i = 0 // statement 1
integer sum = 0 // statement 2
while ( i < 5 ) // statement 3
{
sum = i*i // statement 4
i = i + 1 // statement 5
}
print sum // statement 6
Is her program correct? If not, which statement will you modify to correct it?
Op 1: No error, the program is correct.
Op 2: Statement 1
Op 3: Statement 4
Op 4: statement 6
Correct Op : 3
Q) Shashi wants to make a program to print the sum of the first 10 multiples of 5. She writes the following program, where statement 5 is missing:
integer i = 0
integer sum = 0
while ( i <= 50 )
{
sum = sum + i
-- MISSING STATEMENT 5 --
}
print sum
Which of the following will you use for statement 5?
Op 1: i = 5
Op 2: i = 5 * i
Op 3: i = i + 1
Op 4: i = i + 5
Correct Op : 4
Q) Shantanu wants to make a program to print the sum of the first 7 multiples of 6. He writes the following program:
integer i = 0 // statement 1
integer sum // statement 2
while ( i <= 42 ) // statement 3
{
sum = sum + i // statement 4
i = i + 6;
}
print sum // statement 6
Does this program have an error? If yes, which one statement will you modify to correct the program?
Op 1: Statement 1
Op 2: Statement 2
Op 3: Statement 3
Op 4: Statement 4
Correct Op : 2
Q) Sharmili wants to make a program to print the sum of all perfect cubes, where the value of the cubes go from 0 to 100. She writes the following program:
integer i = 0, a // statement 1
integer sum = 0;
a = ( i * i * i )
while ( i < 100 ) // statement 2
{
sum = sum + a // statement 3
i = i + 1
a = ( i * i * i ) // statement 4
}
print sum
Does this program have an error? If yes, which one statement will you modify to correct the program?
Op 1: Statement 1
Op 2: Statement 2
Op 3: Statement 3
Op 4: Statement 4
Op 5: No error
Correct Op : 2
Q) Bhavya wants to make a program to print the sum of all perfect squares, where the value of the squares go from 0 to 50. She writes the following program:
integer i = 1, a // statement 1
integer sum = 0
while ( a < 50 ) // statement 2
{
sum = sum + a // statement 3
i = i + 1
a = ( i * i ); // statement 4
}
print sum
Does this program have an error? If yes, which one statement will you modify to correct the program?
Op 1: Statement 1
Op 2: Statement 2
Op 3: Statement 3
Op 4: Statement 4
Op 5: No error
Correct Op : 1
6) Vijay wants to print the following pattern on the screen:
2
2 4
2 4 6
2 4 6 8
He writes the following program:
integer i = 1, j=2 // statement 1
while ( i <= 4 ) // statement 2
{
j = 2;
while ( j <= ? ) // Statement 3
{
print j
print blank space
j = j + 2
}
print end-of-line \takes the cursor to the next line
i = i + 1
}
What is the value of ? in statement 3 ::
Op 1: 8
Op 2: i
Op 3: 2*i
Op 4: 4
Correct Op : 3
Shravanti writes the following program:
integer i = 0, j
while ( i < 2 )
{
j = 0;
while ( j <= 3*i )
{
print j
print blank space
j = j + 3
}
print end-of-line \takes the cursor to the next line
i = i + 1
}
What will be the output of the program?
Op 1:
0
0 3
Op 2:
0 3
0 3 6
Op 3:
0
0 3 6
0 3 6 9
Op 4:
0 3 6
0 3 6 9
0 3 6 9 12
Correct Op : 1
Q) Vijay wants to print the following pattern on the screen:
1
1 2
1 2 3
He writes the following program:
integer i = 1 // statement 1
while ( i <= 3 )
{
int j // Statement 2
while ( j <= i ) // Statement 3
{
print j
print blank space
j = j + 1 // Statement 4
}
print end-of-line \takes the cursor to the next line
i = i + 1
}
Will this program function correctly? If not which one statement will you modify to make the program function correctly?
Op 1: Statement 1
Op 2: Statement 2
Op 3: Statement 3
Op 4: Statement 4
Op 5: Program does not have error.
Correct Op : 2
Q) Charu writes the following program:
integer i = 1, j, a
while ( i <= 4 )
{
j = 1;
a = 0;
while ( a <= 5*i )
{
a = 2^j;
print a
print blank space
j = j + 1
}
print end-of-line \takes the cursor to the next line
i = i + 1
}
What will be the output of the program?
Op 1:
2
2 4
2 4 8
2 4 8 16
Op 2:
2 4
2 4 8
2 4 8 16
2 4 8 16 32
Op 3:
2 4
2 4 8
2 4 8
2 4 8 16
Op 4:
2
2 4
2 4
2 4 8 16
Correct Op : 3
Q) Vikram wants to write a program which checks whether the inputted number is divisible by any of the first 6 natural numbers (excluding 1). He writes the following efficient code for it.
int number, n = 2, isdivisible=0
input number
while ( n <=6) // Statement 1
{
if ( remainder (number, n) == 0)
isdivisible = 1
end
n = n+1 // Statement 2
}
if (isdivisible equals 1)
print "It is divisible"
else
print "It is not divisible"
end
Vikram takes the program to Hari. Hari tells Vikram that though the code is correct, it can be made more efficient. Hari modifies a single statement and makes the code more efficient. Which statement does he modify and how?
Op 1: Statement 1 is changed to:
while (n <=6 AND isdivisible=0)
Op 2: Statement 1 is changed to:
while (n <=6 OR isdivisible=0)
Op 3: Statement 1 is changed to:
while (isdivisible=0)
Op 4: Statement 2 is changed to:
n = n + 2
Correct Op : 1