In our day to day life in numerous applications we need to perform tasks that are repetitive in nature. It is a tedious process to perform such a kind of task repeatedly with pen/pencil and paper. But with computer programming languages and packages, the task becomes easy, accurate and fast. For example, the salary of laborers of a factory can be calculated by a formula (number of hours worked × wage rate per hour). The accounts department of each organization is involved in performing this type of calculation every month/week. Such a type of repetitive deeds can be easily done using a loop or iterative structure in a program.
A loop is defined as a block of statements that are repeatedly executed for certain number of times even though those block statements appear only once in the program.
Loops are of two types and they are as follows:
Steps in loop
Loop Variable: It is a variable used in the loop.
Initialization: It is the first step in which starting and final value is assigned to the loop variable. Each time the updated value is checked by the loop itself.
Incrimination/Decrimination: It is the numerical value added or subtracted to the variable in each round of the loop. The updated value is compared with the final value and if it is found to be less than final value the steps in the loop are executed.
The above steps are implemented in numerous programs in this chapter.
The ‘C++’ language supports three types of loop control statements. Their syntaxes are described as given in Fig. 6.1.
for
|
while |
do-while |
---|---|---|
for (expression 1; expression 2; expression 3) statement ; |
expression 1; while (expression 2) { Statement; expression 3; } |
expression 1; do { statement; expression 2; } while (expression 3); |
Fig. 6.1 Syntaxes of various loops.
The for loop comprises three actions. The three actions are placed in the for statement itself. The three actions initialize counter, test condition and re-evaluation parameters are included in one statement. The expressions are separated by semi-colons (;). This leads to the programmer to visualize the parameters easily. The for statement is equivalent to the while and do-while statements. The only difference between for and while is later checks the logical condition and then executes the body of the loop, whereas in the for statement test is always performed at the beginning of the loop. The body of the loop may not be executed at all times if the condition fails at the beginning. The do-while loop executes the body of the loop at least once regardless of the logical condition.
The for loop allows one to execute a set of the instructions until a condition is met. The condition may be predefined or open-ended. Although all programming languages provide for loops still the power and flexibility provided by C/C++ is worth mentioning. The general syntax for the for loop is as follows Fig. 6.2.
Fig. 6.2 for loop
An example of the for loop is as shown in Fig 6.3.
Fig. 6.3 The for loop
Although many variations of for loop are allowed but the simplest form is as shown in Fig. 6.3.
The ‘initialization’ is an assignment statement that is used to set the loop control variable(s). The ‘condition’ is a relational expression that determines the number of the iterations desired or the condition to exit the loop. The ‘increment’ or the re-evaluation parameter decides how to change the state of the variable(s) (quite often increase or decrease so as to approach the limit). These three sections must be separated by semi-colon (;). The body of the loop may consist of a block of statements (which have to be enclosed in braces) or a single statement (enclosure within braces is not compulsory but advised).
Flow chart of for loop is as shown in Fig. 6.4.
Fig. 6.4 Flow chart of for loop
The following programs serve as examples for the for loop.
6.1 |
6.2
|
6.3 |
---|---|---|
#include #include int main() { int j;
for (j=1; cout<<“ ”<<j; return 0; } |
#include #include int main() { clrscr(); int j=0;
for (;j cout<<“ ”<<j; return 0; } |
#include <iostream.h> #include int main() { clrscr(); int j=0;
for (;j<11;) { cout<<“ ”<<j; ++j; } return 0; } |
OUTPUT 1 2 3 4 5 6 7 8 9 10 |
OUTPUT 0 1 2 3 4 5 6 7 8 9 10 |
OUTPUT 0 1 2 3 4 5 6 7 8 9 10 |
Explanation: In this program initialization, condition and increment is done in single parenthesis. |
Explanation: In this program initialization is done before for statement. In for statement only test condition and increment operations are done. |
Explanation: In this program initialization is done before for statement. Increment is done inside the loop. The for loop contains only test condition. |
6.4 Write a program to display all leap years from 2000 to 2012.
#include<conio.h>
#include<iostream.h>
int main()
{
int i=1999;
clrscr();
cout<<“ Program to print all the leap years from 2000 to 2012 ”;
for(;i++<=2012;)
{
if(i%4==0&&i%100!=0)
cout<<i<<“ ”;
else if(i%100==0&&i%400==0)
cout<<i<<“ ”;
}
return 0;
}
OUTPUT
Program to print all the leap years from 2000 to 2012
2000 2004 2008 2012
Explanation: One must be aware that only those years that are
alone are qualified to be called as leap years. The above program checks for these conditions for all years from 2000 to 2012 and then prints the year if it is leap. Stress is on ‘for’ loop construct and use of ‘if’ and ‘else – if’ in the body.
We can also nest for loop to gain more advantage in some situations. The nesting level is not restricted at all. In body of a ‘for’ loop any number of sub -‘for’ loop(s) may exist.
6.5 Write a program to demonstrate nested for loops.
#include<iostream.h>
#include<conio.h>
int main()
{
int a,b,c;
clrscr();
for (a=1;a<=2;a++) // outer loop
{
for (b=1;b<=2;b++) // middle loop
{
for (c=1;c<=2;c++) //inner loop
cout<<“ a=”<<a <<“ + b=”<<b <<“+ c=”<<c <<“:” <<a+b+c;
cout<<“ Inner Loop Over.”;
}
cout<<“ Middle Loop Over.”;
}
cout<<“ Outer Loop Over.”;
return 0;
}
Explanation: The above program will be executed in sequence as per Table 6.1. The total numbers of iterations are equal to 2*2*2 = 8. The final output provides 8 results.
Table 6.1 Working and output of program 6.5
Values of loop variables | ||
---|---|---|
Outer |
Middle |
Inner |
(1) a=1 | b=1 |
c=1 |
(2) a=1 | b=1 |
c=2 |
(3) a=1 | b=2 |
c=1 |
(4) a=1 | b=2 |
c=2 |
Inner Loop Over | ||
Middle Loop Over | ||
(5) a=2 | b=1 |
c=1 |
(6) a=2 | b=1 |
c=2 |
Inner Loop Over | ||
(7) a=2 | b=2 |
c=1 |
(8) a=2 | b=2 |
c=2 |
Inner Loop Over | ||
Middle Loop Over | ||
Outer Loop Over |
Another kind of loop structure in C/C++ is the while loop. Its format is as given in Fig. 6.5.
Syntax:
while (test condition)
{
body of the loop
}
Fig. 6.5 The while loop
The test condition may be any expression. The loop statements will be executed till the condition is true, i.e. the test condition is evaluated and if the condition is true, then the body of the loop is executed. When the condition becomes false the execution will be out of the loop.
The execution of the while loop can be followed by Fig. 6.6.
Fig. 6.6 Flow chart for while-loop
Here, the block of the loop may either contain single statement or a number of statements. The same block can be repeated. The braces are needed only if the body of the loop contains more than one statement. However, it is a good practice to use braces even if the body of the loop contains only one statement.
Steps of while loop are as follows.
Given below are a few example problems on while loop.
6.6 Write a program to add 10 consecutive numbers starting from 1. Use the while loop.
#include<iostream.h>
#include<conio.h>
int main()
{
int a=1,sum=0;
clrscr();
while (a<=10)
{
cout<<“ ”<<a;
sum=sum+a;
a++;
}
cout<<“ Sum of 10 numbers :”<<sum;
return 0;
}
OUTPUT
1 2 3 4 5 6 7 8 9 10
Sum of 10 numbers : 55
Explanation: In the above program integer variable ‘a’ is initialized to 1 and variable ‘sum’ to 0. The while loop checks the condition for a<=10. The variable ‘a’ is added to variable ‘sum’ and each time ‘a’ is incremented by 1. In each while loop ‘a’ is incremented and added to ‘sum’. When the value of ‘a’ reaches 11, the condition given in while loop becomes false. At last the loop is terminated. The sum of the number is displayed.
6.7 Write a program to calculate the sum of the individual digits of an entered number.
#include<iostream.h>
#include<conio.h>
int main()
{
int num,t;
clrscr();
cout<<“ Enter number :”;
cin>>num;
int sum=0;
while(num!=0) //condition is true until num!=0
{
sum=sum+num%10;
}
cout<<“ Sum of the individual digits of the number” <<t<<“ is = ”<<sum;
return 0;
}
OUTPUT
Enter number : 234
Sum of the individual digits of the number 234 is = 9
Explanation: The logic behind the program is to extract each time the LSD(lower significant digit). Each time divide the number by 10 so as to shift it by one place ). To extract the LSD we use the fact that num % 10 = the remainder on dividing num by 10.
6.8 Write a program to check whether the entered number is a palindrome or not.
#include<iostream.h>
#include<conio.h>
int main()
{
int num;
clrscr();
cout<<“ Enter the number :”;
cin>>num;
int b=0,a=num;
while(a)
{
b=b*10+a%10;
a=a/10;
}
if(num==b)
cout<<“ The given number is palindrome”;
else
cout<<“ The given number is not palindrome”;
return 0;
}
OUTPUT
Enter the number: 121
The given number is palindrome
Explanation: Palindrome number is a number that is equal to its reverse (e.g. 51715). The above program first reverses the number and stores it in ‘b’. Then it compares ‘b’ with original number to tell you whether or not the number is a palindrome. See that in each iteration the LSD of ‘a’ is being made MSD of ‘b’.’The ‘a’ is being shifted left and ‘b’ is shifted right by one digits in every iteration. Iterations are being done until ‘a’ exhausts or becomes equal to 0.
The format of do-while loop in C/C++ is as follows (Fig 6.7)
do
{
statement/s;
}
while (condition);
Fig. 6.7 do-while loop
The difference between the while and do-while loop is the place/position where the condition is to be tested. In the while loops the condition is tested following the while statement and then the body gets executed. Whereas in the do-while the condition is checked at the end of the loop. The do-while loop will execute at least one time even if the condition is false initially. The do-while loop executes until the condition becomes true. Table 6.2 shows the comparison between the while and do-while loops.
Table 6.2 Comparison of while and do-while loop.
Sr No
|
while-loop |
do–while |
---|---|---|
1 |
Condition is specified at the top |
Condition is mentioned at the bottom |
2 |
Body statement/s is/are executed when condition is satisfied |
Body statement/s execute even when condition is false |
3 |
No brackets for a single statement |
Brackets are essential even when a single statement exit |
4 |
It is entry controlled loop |
It is exit controlled loop |
Programs on do-while loop are as follows.
6.9 Write a program using do-while loop to print numbers and their cubes up to 10.
#include<iostream.h>
#include<conio.h>
#include<math.h>
int main()
{
int y,x=1;
clrscr();
cout<<“ Numbers and their cubes ”;
do
{
y=pow(x,3);
cout<<“ ”<<x<<“ ”<<y<<“ ”;
x++;
}
}
OUTPUT
Numbers and their cubes
1 |
1 |
2 |
8 |
3 |
27 |
4 |
64 |
5 |
125 |
6 |
216 |
7 |
343 |
8 |
512 |
9 |
729 |
10 |
1000 |
Explanation: Here, the mathematical function pow (x,3) is used from the library. It’s meaning is to calculate the third power of x. With this function we get the value of y=x3. For use of the pow() function we have to include math.h header file.
The format of do-while with multiple while statements loop is as shown in Fig. 6.8.
do while(condition)
{
statement/s;
}
while (condition);
Fig. 6.8 Syntax of do-while with multiple while statement
6.10 Write a program to add numbers from 0 to 5 using while statement in do-while loop.
#include<iostream.h>
#include<conio.h>
int main()
{
int sum=0,x=0;
clrscr();
do while (x<5)
{
x++;
}
while(x>5);
cout<<“ Sum of numbers from 0 to 5:”<<sum;
return 0;
}
OUTPUT
Sum of numbers from 0 to 5: 15
Explanation: Initially the value of x and sum are 0. Value of x is incremented in and added with the sum in each iteration. With do-while loop the value of x is incremented and when it is greater than 5 the outer while loop is executed.
6.11 Write a program to use break statement and terminate the loop.
#include<iostream.h>
#include<conio.h>
int main()
{
int x=1;
clrscr();
while (1)
{
cout<<“ ”<<x;
if (x==8)
break;
x++;
}
return 0;
}
OUTPUT
1 2 3 4 5 6 7 8
Explanation: In the above program the while loop is an infinite loop. The integer variable x is initialization to 1. In each iteration the value of x is displayed and incremented. The if condition checks the value of x with 8. If the value of x is equal to 8 the break statement is executed and the infinite while loop terminates. Thus, the break statement is used to exit from the loop as per shown in Fig. 6.9
Fig. 6.9 Working of break statement
6.12 Write a program to demonstrate the use of continue statement.
#include<iostream.h>
#include<conio.h>
int main()
{
int x=1;
clrscr();
for(;x<=50;x++)
{
if (x%2==0)
continue;
cout<<“ ”<<x;
}
return 0;
}
OUTPUT
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
Explanation: In the above program the for loop executes from 1 to 50. The if condition check whether the remainder of number is 0 or non –zero. If the remainder is zero, the continue statement is executed and the statement after continue statement will not be executed. The continue statement transfers the control at the beginning of the loop. Fig. 6.10 simulates the working of continue statement.
Fig. 6.10 Working of continue statement
(A) Answer the following questions
(B) Answer the following by selecting the appropriate option
i++,j++) {-----}
(C) Attempt the following programs
Use (.) dot for seconds pointer.
Use (*) star for minutes pointer.
Use (#) hash for hours pointer.
a + 1 + b + 2 + c + 3 + ··· + n, where n is an integer.
z + y + x + ··· + a.
za + yb + xc + ··· + az.
If n =10, generate 2 4 6 8 10.
If n =11, generate 1 3 5 7 11.