Home | | Computer Science 11th std | C++ Iteration statements

Flow of Control | C++ - C++ Iteration statements | 11th Computer Science : Chapter 10 : Flow of Control

Chapter: 11th Computer Science : Chapter 10 : Flow of Control

C++ Iteration statements

An iteration (or looping) is a sequence of one or more statements that are repeatedly executed until a condition is satisfied.

Iteration statements

 

An iteration (or looping) is a sequence of one or more statements that are repeatedly executed until a condition is satisfied. These statements are also called as control flow statements. It is used to reduce the length of code, to reduce time, to execute program and takes less memory space. C++ supports three types of iteration statements;

i. for statement

ii. while statement

iii. do-while statement

All looping statements repeat a set statements as long as a specified condition is remains true. The specified condition is referred as a loop control. For all three loop statements, a true condition is any nonzero value and a zero value shows a false condition.

 

Parts of a loop

 

Every loop has four elements that are used for different purposes. These elements are

• Initialization expression

• Test expression

• Update expression

• The body of the loop

Initialization expression(s): The control variable(s) must be initialized before the control enters into loop. The initialization of the control variable takes place under the initialization expressions. The initialization expression is executed only once in the beginning of the loop.

Test Expression: The test expression is an expression or condition whose value decides whether the loop-body will be execute or not. If the expression evaluates to true (i.e., 1), the body of the loop executed, otherwise the loop is terminated.

In an entry-controlled loop, the test-expression is evaluated before the entering into a loop whereas in an exit-controlled loop, the test-expression is evaluated before exit from the loop.

Update expression: It is used to change the value of the loop variable. This statement is executed at the end of the loop after the body of the loop is executed.

The body of the loop: A statement or set of statements forms a body of the loop that are executed repetitively. In an entry-controlled loop, first the test-expression is evaluated and if it is nonzero, the body of the loop is executed otherwise the loop is terminated. In an exit-controlled loop, the body of the loop is executed first then the test-expression is evaluated. If the test-expression is true the body of the loop is repeated otherwise loop is terminated

 

for loop

 

The for loop is the easiest looping statement which allows code to be executed repeatedly. It contains three different statements (initialization, condition or test-expression and update expression(s)) separated by semicolons.

 

The general syntax is:

for (initialization(s); test-expression; update expression(s))

{

      Statement 1;

      Statement 2;

      ………….

}

Statement-x;

The initialization part is used to initialize variables or declare variable which are executed only once, then the control passes to test-expression. After evaluation of test-expression, if the result is false, the control transferred to statement-x. If the result is true, the body of the for loop is executed, next the control is transferred to update expression. After evaluation of update expression part, the control is transferred to the test-expression part. Next the steps 3 to 5 is repeated. The workflow of for loop and flow chart are shown below.


 

Illustration 10.11 C++ program to display numbers from 0 to 9 using for loop

#include <iostream>

using namespace std;

int main ()

{

int i;

for(i = 0; i< 10; i ++ )

      cout<< "value of i : " <<i<<endl;

return 0;

}

Output

value of i : 0

value of i : 1

value of i : 2

value of i : 3

value of i : 4

value of i : 5

value of i : 6

value of i : 7

value of i : 8

value of i : 9

 

The following lines describes the working of the above given for loop:


In the above program, first the variable i is initialized, next i is compared with 10, if i is less than ten, the value of i is incremented. In this way, the numbers 0 to 9 are displayed. Once i becomes 10, it is no longer < 10. So, the control comes out of the for loop.

 

Illustration 10.12 C++ program to sum the numbers from 1 to 10 using for loop

#include <iostream>

using namespace std;

int main ()

{

int i,sum=0;

for(i=1; i<=10;i++)

{

      sum=sum+i;

}

cout<<"The sum of 1 to 10 is "<<sum;

return 0;

}

Output

The sum of 1 to 10 is 55

 

Variations of for loop

The for is one of the most important looping statement in C++ because it allows a several variations. These variations increase the flexibility and applicability of for loop. These variations will be discussed below:

 

Multiple initialization and multiple update expressions

Multiple statements can be used in the initialization and update expressions of for loop. These multiple initialization and multiple update expressions are separated by commas. For example,


Output

The value of i is 0 The value of j is 10

The value of i is 1 The value of j is 9

The value of i is 2 The value of j is 8

The value of i is 3 The value of j is 7

The value of i is 4 The value of j is 6

In the above example, the initialization part contains two variables i and j and update expression contains i++ and j++. These two variables are separated by commas which is executed in sequential order i.e., during initialization firstly i=0 followed by j=10. Similarly, in update expression, firstly i++ is evaluated followed by j++ is evaluated.

 

Prefer prefix operator over postfix

Generally, the update expression contains increment/decrement operator (++ or --). In this part, always prefer prefix increment/decrement operator over postfix when to be used alone. The reason behind this is that when used alone, prefix operators are executed faster than postfix.

 

Optional expressions

Generally, the for loop contains three parts, i.e., initialization expressions, test expressions and update expressions. These three expressions are optional in a for loop.

 

Case 1

Illustration 10.13 (a) C++ program to sum the numbers from 1 to 10

#include <iostream>

using namespace std;

int main ()

{

int i, sum=0, n;

cout<<"\n Enter The value of n";

cin>>n;

i =1;

for ( ; i<=10;i++)

      {

      sum += i;

     }

cout<<"\n The sum of 1 to " <<n<<"is "<<sum;

return 0;

}

Output

Enter the value of n 5

The sum of 1 to 5 is 15

 

In the above example, the variable i is declared and sum is initialized at the time of variable declaration. The variable i is assigned to 0 before the for loop but still the semicolon is necessary before test expression. In a for loop, if the initialization expression is absent then the control is transferred to test expression/conditional part.

 

Case 2

Illustration 10.13 (b) C++ program to sum the numbers from 1 to 10

#include <iostream>

using namespace std;

int main ()

{

int i, sum=0, n;

cout<<"\n Enter The value of n";

cin>>n;

i =1;

for ( ; i<=10; )

{

      sum += i;

      ++i;

}

cout<<"\n The sum of 1 to " <<n<<"is "<<sum;

return 0;

}

Output

Enter the value of n 5

The sum of 1 to 5 is 15

 

In the above code, the update expression is not done, but a semicolon is necessary before the update expression.


In the above code, neither the initialization nor the update expression is done in the for loop.

If both or any one of expressions are absent then the control is transferred to conditional part.

 

Case 3

An infinite loop will be formed if a test-expression is absent in a for loop. For example,


Similarly, the following for loop also forms an infinite loop.


 

Empty loop

Empty loop means a loop has no statement in its body is called an empty loop. Following for loop is an empty loop:


In the above code, the for loop contains a null statement, it is an empty loop.

Similarly, the following for loop also forms an empty loop.


In the above code, the body of a for loop enclosed by braces is not executed at all because a semicolon is ended after the for loop.

 

Declaration of variable in a for loop

In C++, the variables can also be declared within a for loop. For instance,


A variable declared inside the block of main() can be accessed anywhere inside main() i.e., the scope of variable in main()

 

While loop

 

A while loop is a control flow statement that allows the loop statements to be executed as long as the condition is true. The while loop is an entry-controlled loop because the test-expression is evaluated before the entering into a loop.

The while loop syntax is:

while ( Test expression )

{

      Body of the loop;

}

Statement-x;

The control flow and flow chart of the while loop is shown below.


Flowchart 10.7: while loop control flow and while loop flowchart

In while loop, the test expression is evaluated and if the test expression result is true, then the body of the loop is executed and again the control is transferred to the while loop. When the test expression result is false the control is transferred to statement-x.

 

Illustration 10.14 C++ program to sum numbers from 1 to 10 using while loop

#include <iostream>

using namespace std;

int main ()

{

int i=1,sum=0;

while(i<=10)

{

      sum=sum+i;

      i++;

}

cout<<"The sum of 1 to 10 is "<<sum;

return 0;

}

Output

The sum of 1 to 10 is 55

 

In the above program, the integer variable i is initialized to 1 and the variable sum to 0. The while loop checks the condition, i < 10, if the condition is true, the value of i, which is added to sum and i is incremented by 1. Again, the condition i < 10 is checked. Since 2 < 10, 2 is added to the earlier value of sum. This continues until i becomes 11. At this point in time, 11< 10 evaluates to false and the while loop terminates. After the loop termination, the value of sum is displayed.

 

Illustration 10.15 C++ program to sum numbers from 1 to 10 using while loop

#include <iostream>

using namespace std;

int main ()

{

int i=1,num,avg,sum=0;

while(i<=5)

{

      cout<<"Enter the number : ";

      cin>>num;

      sum=sum+num;

      i++;

}

avg=sum/5;

cout<<"The sum is "<<sum<<endl;

cout<<"The average is "<<avg;

return 0;

}

Output

Enter the number : 1

Enter the number : 2

Enter the number : 3

Enter the number : 4

Enter the number : 5

The sum is 15

The average is 3

In the above program, integer variables num and avg are declared and variable i is initialized to 1 and sum to 0. The while loop checks the condition, since i <= 5 the condition is true, a number is read from the user and this is added to sum and i is incremented by 1. Now, the condition is i <= 5 is again checked. Since 2 <=5, the second number is obtained from the user and it is added to sum. This continues, until i becomes 6, at which point the while loop terminates. After the loop termination, the avg is computed and both sum and avg are displayed.

 

While loop variation

A while loop may contain several variations. It can be an empty loop or an infinite loop. An empty while loop does not have any statement inside the body of the loop except null statement i.e., just a semicolon.

For example


In the above code, the loop is a time delay loop. A time delay loop is useful for pausing the program for some time.

A while loop may be infinite loop when no update statement inside the body of the loop. For example,


Similarly, there is another variation of while is also shown below:

int main()

{

      int i=1;

      while( ++i < 10)

      cout<< “The value of i is “<<i;

      return 0;

}

In the above statement while ( ++i < 10 ), first increment the value of i, then the value of i is compared with 10.

int main()

{

      int i=1;

      while( i++ < 10)

      cout<< “The value of i is “<<i;

      return 0;

}

In the above statement while ( i++ < 10 ), first the value of i is compared with 10 and then the incrementation of i takes place. When the control reaches cout<< “The value of i is “<<i statement, i has already been incremented.

 

do-while loop

 

The do-while loop is an exit-controlled loop. In do-while loop, the condition is evaluated at the bottom of the loop after executing the body of the loop. This means that the body of the loop is executed at least once, even when the condition evaluates false during the first iteration.

The do-while loop syntax is:

do

{

      Body of the loop;

} while(condition);

The flow control and flow chart do-while loop is shown below


Flowchart 10.8 : do-while loop control flow and do-while loop flowchart

 

Illustration 10.16 C++ program to display number from 10 to 1 using do-while loop

#include <iostream>

using namespace std;

int main ()

{

int n = 10;

do

{

      cout<<n<<", ";

      n--;

}while (n>0) ;

}

Output

10, 9, 8, 7, 6, 5, 4, 3, 2, 1

 

In the above program, the integer variable n is initialized to 10. Next the value of n is displayed as 10 and n is decremented by 1. Now, the condition is evaluated, since 9 > 0, again 9 is displayed and n is decremented to 8. This continues, until n becomes equal to 0, at which point, the condition n > 0 will evaluate to false and the do-while loop terminates.


Nesting of loops

 

A loop which contains another loop is called as a nested loop.

The syntax is given below:

for (initialization(s); test-expression; update expression(s))

{

      for (initialization(s); test-expression; update expression(s)

      {

      statement(s);

      }

statement(s);

}


 

Illustration 10.17 C++ program to display matrix multiplication table using nested for loop

#include<iostream>

using namespace std;

int main(void)

{

      cout<< "A multiplication table:" <<endl <<" 1\t2\t3\t4\t5\t6\t7\t8\t9" <<endl<< "" <<endl;

      for(int c = 1; c < 10; c++)

      {

      cout<< c << "| ";

      for(int i = 1; i< 10; i++)

      {

      cout<<i * c << '\t';

      }

      cout<<endl;

      }

return 0;

}

Output

A multiplication table:    

1    2   3      4        5        6        7        8        9

1| 1     2      3        4        5        6        7        8        9

2| 2     4      6        8        10      12      14      16      18

3| 3     6      9        12      15      18      21      24      27

4| 4     8      12      16      20      24      28      32      36

5| 5     10    15      20      25      30      35      40      45

6| 6     12    18      24      30      36      42      48      54

7| 7     14    21      28      35      42      49      56      63

8| 8     16    24      32      40      48      56      64      72

9| 9     18    27      36      45      54      63      72      81

 

Tags : Flow of Control | C++ , 11th Computer Science : Chapter 10 : Flow of Control
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 10 : Flow of Control : C++ Iteration statements | Flow of Control | C++


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.