Chapter 6

Control Loop Structures

CHAPTER OUTLINE
6.1  INTRODUCTION

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.

6.2  WHAT IS A LOOP?

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:

  1. Counter-controlled repetition
  2. Sentinel-controlled repetition
  1. Counter-controlled repetition: This is also called definite repetitive actions, because in advance the number of iterations to be performed is defined in the program itself. The steps for performing counter-controlled repetitions are given below.

    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.

  2. Sentinel-controlled repetition: This is also called indefinite repetitive actions. One cannot estimate the number of iterations to be performed. In this type loop, termination happens based on certain conditions using decision-making statement.

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.

6.3  THE for LOOP

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.

 

Syntax of for loop

for (initialization; test-condition; increment/

decrement)

{

Statement;

}

Fig. 6.2 for loop

An example of the for loop is as shown in Fig 6.3.

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

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
<iostream.h>

#include
<conio.h>

int main()

{

clrscr();

int j;

 

for (j=1;
j<11;j++)

cout<<“ ”<<j;

return 0;

}

#include
<iostream.h>

#include
<conio.h>

int main()

{

clrscr();

int j=0;

 

for (;j
<11;j++)

cout<<“ ”<<j;

return 0;

}

#include <iostream.h>

#include
<conio.h>

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

#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

  • divisible by 4 and not 100,
  • divisible by 100 and also 400

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.

6.4  NESTED for LOOPS

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

Inner Loop Over

(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

6.5  THE while LOOP

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

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.

  1. The test condition is evaluated, and if it is true, the body of the loop is executed.
  2. On execution of the body, and updating the variable test condition is repeatedly checked. If it is true the body is executed.
  3. In case the test condition fails the control transfer out of the loop or stop.

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

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

num=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.      image

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

6.6  THE do-while LOOP

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

}

while (x<=10);

}

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.

6.7  THE do-while STATEMENT WITH while LOOP

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

      sum=sum+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.8  MORE PROGRAMS

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

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

Fig. 6.10 Working of continue statement

SUMMARY
  1. This chapter discusses the basics of control structure of C++ language.
  2. The C++ control structure covers certain operations that are performed repetitively called as loop statements.
  3. C/C++ has four statements that perform an unconditional control transfer. These are return, goto, and break and continue. Of these, return is used only in functions. goto and return may be used anywhere in the program but continue and break statements may be used only in conjunction with a loop statement.
  4. 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 for statement is equivalent to the while and do-while statements. The only difference between for and while is that the latter checks the logical condition and then executes the body of the loop, whereas 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.
EXERCISES

(A) Answer the following questions

  1. Explain the need of control structure in C++.
  2. What are the differences between break and continue?
  3. What are the differences between while and do-while loop statements?
  4. What is an infinite loop?
  5. What happens if you create a loop that never ends?
  6. Is it possible to create a for loop that is never executed?
  7. What is a loop? Why it is necessary in the program?
  8. Is it possible to nest while loop within for loops?
  9. What is the difference between (!0) and (!1). How does the while loop work with these values?
  10. Is it possible to use multiple while statements with the do statement?

(B) Answer the following by selecting the appropriate option

  1. The following loop statement uses two keywords
    1. do-while loop
    2. for loop
    3. while loop
    4. none of the above
  2. The correct syntax of ‘for’ loop is
    1. for(i=0;i<n;i++) {----}
    2. for( i=0,j=0;i<n && j<n;

      i++,j++) {-----}

    3. for(i=0;i++<n;){-----}
    4. All of these
  3. This loop statement is terminated by semicolon
    1. do-while loop
    2. for loop
    3. while loop
    4. none of the above
  4. Every expression always returns
    1. 0 or 1
    2. 1 or 2
    3. –1 or 0
    4. none of the above
  5. In a nested loop
    1. the innermost loop is completed first
    2. the outermost loop is completed first
    3. both (a) and (b)
    4. none of the above

(C) Attempt the following programs

  1. Write a program to display numbers from 10 to 1 using for loop.
  2. Write a program to calculate the factorial of a given number.
  3. Write a program to display only even numbers between 1 and 150.
  4. Write a program to solve the series x=1/2!+1/4!+1/n!.
  5. Write a program to calculate the sum of numbers between 1 to N numbers. The user enters the value of N.
  6. Write a program to use break and continue statement.
  7. Write a program to display alphabets A to Z using while loop.
  8. Write a program to display alphabets as given below.
    az by cx dw ev fu gt hs Ir jq kp lo mn nm ol pk qj ri sh tg uf ve wd xc yb za.
  9. Write a program to display count values from 0 to 100 and flash each digit for one second. Reset the counter after it reaches to hundred. The procedure is to be repeated. Use for loop.
  10. Develop a program to simulate a seconds clock. Put 60 dots on the circle with equal distance between each other and mark them 0 to 59. A seconds pointer is to be shown with any symbol. Also print the total number of revolutions made by the second’s pointer.
  11. Write a program to simulate an analog watch (numbers 1 to 12 to be arranged in circular fashion with all the three pointers for seconds, minutes, and hours) on the screen. Use nested for loops.

    Use (.) dot for seconds pointer.

    Use (*) star for minutes pointer.
    Use (#) hash for hours pointer.

  12. Write a program to calculate the sum of first and last number from 1 to 10 (Example 1 + 10, 2 + 9, 3 + 8; sums should be always 11).
  13. Write a program to find the total number of votes in favor of persons ‘A’ and ‘B’. Assume 100 voters will be casting their votes to these persons. Count the number of votes gained by ‘A’ and ‘B’. The user can enter his/her choices by pressing only ‘A’ or ‘B’.
  14. Write a program to pass the resolution in a meeting comprising of five members. If three or more votes are obtained the resolution is passed otherwise rejected.
  15. Assume that there are 99 voters voting to a person for selecting chairman’s candidature. If he secures more than 2/3 votes he should be declared as chairman otherwise his candidature will be rejected.
  16. Write a program to display the numbers of a series 1, 3, 9, 27, 81…. n, by using for loop.
  17. Write a program to check that entered input data for the following. Whenever input is non-zero or positive display numbers from 1 to that number otherwise display message “Negative or zero”. The program is to be performed for 10 numbers.
  18. Write a program to check entered data types for 10 times. If a character is entered print “Character is entered” otherwise “Numeric is entered” for numerical values.
  19. Write a program to find the sum of the first hundred natural numbers (1 + 2 + 3 + ··· 100).
  20. Write a program to display numbers 11, 22, 33,…, 99 using ASCII values from 48 to 57 in loops.
  21. Create an infinite for loop. Check each value of the for loop. If the value is odd, display it otherwise continue with iterations. Print even numbers from 1 to 100. Use break statement to terminate the program.
  22. Write a program to display the alphabets as a rectangle as shown below.
    image
  23. Write a program to read ten numbers through the keyboard and count the number of positive, negative and zero numbers.
  24. Write a nested for loop that prints a 5 X 10 pattern of 0s.
  25. Is it possible to create a loop using goto statement? If yes write the code for it.
  26. Write a program to find the triangular number of a given integer. For example triangular of 5 is (1 + 2 + 3 + 4 + 5) 15. Use do-while loop.
  27. Write a program to display all ASCII numbers and their equivalent character numbers and symbols. Use do-while loop. User should prompt every time to press ‘Y’ or ‘N’. If the user presses ‘Y’ display next alphabet otherwise terminate the program.
  28. Accept any five one-digit numbers. If the first number is smaller than the second, then display the sum of squares; otherwise, display the sum of cubes of all.
  29. Evaluate the following series. Use do-while loop.
    1. 1 + 3 + 5 + 7 + ··· + n
    2. 1 + 4 + 25 + 36 + ··· + n
    3. x + x2/2! + x3/3! + ··· + n
    4. 1 + x + x2 + x3 + ··· + xn
  30. Write a program to display the following using do-while loop.

    a + 1 + b + 2 + c + 3 + ··· + n, where n is an integer.

    z + y + x + ··· + a.

    za + yb + xc + ··· + az.

  31. Enter the 10 numbers through the keyboard and sort them in ascending and descending orders, using do-while loop.
  32. Enter text through the keyboard and display it in reverse order. Use do-while loop.
  33. Print multiplication of digits of any number. Fox example number 235, multiplication to be 5*3*2 = 30. Use do-while loop.
  34. Print square roots of each digit of any number. Consider each digit as a perfect square. For example, for the number 494 the square roots to be printed should be 2 3 2.
  35. Write a program to read any positive/negative integer number ‘n’ and generate the numbers in the following way. For example, if the entered number is 3, the output will be 9 4 1 0 1 4 9, else for negative (i.e., –3) the output will be 9 4 1 0 1 2 3.
  36. Write a program to enter two integer values through the keyboard. Using while loop, perform the product of two integers. In case product is zero (0), loop should be terminated otherwise loop will continue.
  37. Write a program to enter a single character either in lower or capital case. Display its corresponding ASCII equivalent number. Use the while loop for checking ASCII equivalent numbers for different characters. When capital ‘E’ is pressed, the program should terminated.
  38. Write a program to read a positive integer number ‘n’ and generate the numbers in the following way. If the entered number is 4 the output will be as follows. OUTPUT: 4! 3! 2! 1! 0 1! 2! 3! 4! 5!.
  39. Write a program to read a positive integer number ‘n’ and generate the numbers in the different ways as given below.

     

    If n =10, generate 2 4 6 8 10.

    If n =11, generate 1 3 5 7 11.

     

  40. Write a program to enter a multiple digit number and find its largest and smallest digits.
  41. Write a program to enter an integer number and find the largest and smallest digits of the number.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset