Looping concepts in C++






Like other modern programming languages, in C++ also we can use the iteration statements or loops in the scenario when we need to
execute a set of instructions or a block of code repeatedly until it meets a specified condition. It is also very useful when we need to iterate
over or traverse a given list or an array of variables. Loops can be classified into three types.

  • for loop
  • while loop
  • do-while loop

Now let see each of them in detail.


for Loop:

General syntax of the "for loop" statement is:

              
                for(intialization; condition; increment){
                  .... 
                  ....
                }
              
            

In the for loop, initialization is the assignment statement which is used to set the variable to control the loop, condition is a relational
expression to determine the condition to exit the loop and increment defines how the loop control variable changes in each repetition of the
loop.
These three must be separated by semicolons. The for loop continues to execute till the condition is True. Once the condition becomes false,
the loop will be terminated and program execution will come out of the for loop.
Below is the flowchart of the "for" loop execution

 blog4

Let check one simple code example of for loop usage.

              
                #include < iostream>
                using namespace std;
                int main() {
                  int y = 0;
                  for(int x = 2; x <= 10; x=x+2){
                    y = x*x;
                    cout<< "Square of " << x << " is " << y << endl; 
                  }
                  return 0;
                }
              
            

Output will be:

              
                Square of 2 is 4
                Square of 4 is 16
                Square of 6 is 36
                Square of 8 is 64
                Square of 10 is 100
              
            

Here we are targeting to find the square of all even integers between 1 to 10. So here we have taken the loop variable "x" and initialize it
with the value "2". In the condition, we are setting the range of "x" by putting put the check "x" is less or equal to "10". So, the for loop will
be executed till the value of "x" is within the range of 1 to 10. And at last, we are increasing the value of "x" by "2" in each iteration of the
loop.


while Loop:

The second loop feature supported by C++ is the "while loop". Its general syntax is as below.

              
                while(condition){
                  statement;
                }
              
            

In the above syntax "condition" may be any expression, and "true" will be any non-zero value. The loop iterates while the condition is "true"
and will be terminated once the condition will be "false". The "statement" is either an empty statement, single statement or multiple
statements.
Below is the flowchart of "while loop" execution.

    blog4

Let's check a simple example of "while loop".

              
                #include < iostream>
                using namespace std;
                int main() {
                  int num = 0;
                  while( num <= 10 ){
                    cout<< "Current value of num is: "<< num << endl; 
                    num++;
                  }
                  return 0;
                }
              
            

Output will be:

              
                Current value of num is: 0
                Current value of num is: 1
                Current value of num is: 2
                Current value of num is: 3
                Current value of num is: 4
                Current value of num is: 5
                Current value of num is: 6
                Current value of num is: 7
                Current value of num is: 8
                Current value of num is: 9
                Current value of num is: 10
              
            

Here "num" is our local variable whose initial value is "0". In the "condition" part we are checking if its value is less than or equal to "10" so
that the "while" loop will be executed till this condition will be true. Once the value of num will exceed the value "10" the loop will break and
the execution will come out of the loop. In the "statement" section we are simply printing the value of "num" and increasing its value by 1 in
each iteration of the loop.


do-while loop:

Unlike the "for" and "while" loop which tests the loop condition first before entering into the loop, the "do-while" loop gives us the provision to
first go through the "statements" once then at bottom of the loop it will check the loop "condition". This means that "do-while" loop always
executes at least once.
Syntax for "do-while" loop is as below.

              
                do{
                  statement;
                }while(condition);
              
            

Below is the flowchart of "do-while" loop execution.

    blog4

Let check its concept with previous example.

              
                #include < iostream>
                using namespace std;
                int main() {
                  int num = 0;
                  do{
                    //num++;
                    cout<< "Current value of num is: "<< num << endl;        
                    num++;                    
                  }while( num <=10 );
                  return 0;
                }
              
            

Output will be:

              
                Current value of num is: 0
                Current value of num is: 1
                Current value of num is: 2
                Current value of num is: 3
                Current value of num is: 4
                Current value of num is: 5
                Current value of num is: 6
                Current value of num is: 7
                Current value of num is: 8
                Current value of num is: 9
                Current value of num is: 10
              
            

Infinite Loop:

Infinite loops are those loops that will execute continuously. In most cases "for loop" is used for this purpose. In this case, none of the loop
conditions are required. Here we need not requires to put any of the three expression in the for loop.
A simple example for the same is below.

              
                #include < iostream>
                using namespace std;
                int main() {
                  for( ; ; ){
                    cout<< "This statement repeats again and again." << endl; 
                  }
                  return 0;
                }
              
            

Output will be:

              
                This statement repeats again and again.
                This statement repeats again and again.
                This statement repeats again and again.
                This statement repeats again and again.
                .. 
                .. 
              
            

Jump Control Statements:

Jump control statements are used to break the execution of the loop in between and comes out of the loop. There are four types of jump
statement supported in C++. Let's check each of them:-

  • return statement:- "return" statement is used to return from a function or a block. It is considered as a jump statement because it will
    return back the control to the point from where the call to the function was made. Its syntax is as below:

                      
                        return expression ;
                      
                    

    Here "return" is the keyword and "expression" will be used to return a value to the calling function. In case if it is not returning any
    value then it should be marked as "0" or should be left empty.

  • goto statement:- "goto" statement requires a "label" for operation. A "label" is an identifier that should be present in the same function
    as the "goto", because it is not allowed to jump between two function using "goto" statement. Whenever the "goto" is encountered the
    execution will jump to the position marked by "label". Although "goto" statement is provided for the ease of programmer, but in good
    coding practice it is always advisable to avoid using "goto" in code because it makes the code unreadable. Syntax of "goto" is as below.

                    
                      goto label ;
                      .. 
                      .. 
                      .. 
                      label :
                    
                  
  • break statement:- "break" statement is used to immediate force termination of a loop, bypassing the normal loop condition check and
    take the control out of the loop. It has another usage in "switch-case" statement to put the break in between the statement. We will cover
    the same in next chapter. One simple usage syntax of "break" is as below.

                    
                      for(int i = 0; i < 50; i++){
                        cout << "Value of i is" << i;
                        if(i == 25)
                          break;
                      }
                    
                  

    In the above example, we had put the "for" loop condition to run it till the value of "i" will less than "50" which means its range is from 0 to
    49. But also inside the for loop, we had explictly put the check that if the value of "i" equals to "25" then break the execution at that point
    and comes out of the loop. So int this "for" loop will run only till the value of "i" equals "25".

  • continue statement:- "continue" statement works similar to "break" statement, the only difference is that instead of forcing the termination, "continue" forces the next iterationof the loop to takes place.