Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Recursion Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess STL Modern C++ Misc Books ----

Loops


Contents

Increment Operators

We have 2 kinds of increment operators; postfix and prefix. Both the operators increment the value of the variable by 1. The difference is when they do it.
File: inc1.cpp
#include <iostream>
using namespace std;

int main()
{
    int x1 = 5 ;
    int y1 = 5 ;
    int z1 ;

    //x1 is still 5 and y1 becomes 6 so z1 is 11
     z1 = x1++ +  ++y1 ;
     //Now x1 s 6     
    //z1 prints 11   
    cout << "z1 = " << z1 << endl ;
    //x1 is 6 and y1 is 6   
     z1 = x1++ +  y1++ ;
     //z1 is 12      
      // x1 is now 7 and y1 is 7  
      cout << "z1 = " << z1 << endl ;
     //12     
      z1 = x1 +  y1 ;
      //z1 is now 14  
      cout << "z1 = " << z1 << endl ;
      //z1 is still 14 and will only change it's value 
      // after the conditional expression  
        if ( z1++ == 14 )
             z1++ ;
     //After the conditional expression z1 is 15 and now we have another "++" so z1 is 16 
      ++z1 ;  //Now z1 is 17  
     cout << "z1 = " << z1 << endl ;
         //17


  }


When the "++" is before the variable then the operator is "prefix" and the change happens immediately. The postfix "++" after the variable means that the change happens in the next step either after the assignment statement or even in a conditional expression or any other expression.


File: dec1.cpp
#include <iostream>
using namespace std;

int main()
{
    int x1 = 12 ;
    int y1 = 12 ;
    int z1 ;
    z1 = x1-- +  --y1 ;
     cout << "z1 = " << z1 << endl ;
    z1 = x1-- +  y1-- ;
    cout << "z1 = " << z1 << endl ;
    z1 = x1 +  y1 ;
    cout << "z1 = " << z1 << endl ;
    if ( z1-- == 20 )
        z1-- ;
   // After the conditional expression z1 is 19
   // and now we have another "--" so z1 is 18
      --z1 ;
      //Now z1 is 17
       cout << "z1 = " << z1 << endl ;

 }

While

We use loops to repeat a statement or group of statements. There are 3 types of loops in C++ "While" , "do while" and the "for" loop. The syntax of the while loop is:

   while ( boolean expression )

        statements
The while loop will test the boolean expression and if true will proceed to execute the statement or a group of statements. Control will then jump back to the boolean expression and it will be evaluated and if true the same sequence of actions is repeated.
File: wh1.cpp
#include <iostream>
using namespace std;



int main()
 {
   int x1, number = 0   ;
   cout << "Enter a number between 1 to 10." ;
   cin >> x1 ;


   while (number < x1 )
    {
             cout << "Hello\n";
             number++;
    }
   return 0 ;

}
In the above we request a number from the user and the loop runs that many number of times executing "cout" every time it does so.

We need to be careful that the condition fails at some point:

File: wh2.cpp
#include <iostream>
using namespace std;

int main()
{
     int x1, number = 0   ;
     cout << "Enter a number between 1 to 10." ;
     cin >> x1 ;
     while (number < x1 )
      {
        cout << "Hello\n";
        //number++; 	
       }
        return 0 ;



}
We commented out the statement "number++;" and as a result the while condition never false and repeats for ever ( an infinite loop ).
File: wh3.cpp
#include <iostream>
using namespace std;

int main() 
{ 
        int x1, number = 0   ;
         cout << "Enter a number between 1 to 10." ;    
         cin >> x1 ;  
          while (number < x1 ) ; 
           {               
                       cout << "Hello\n";
                       number++; 
           }  
       return 0 ;  
}
What does the above program do when run ?
File: wh4.cpp
#include <iostream>
using namespace std;

int main()
{
     int  number = 0   ;
     cout << "Enter a number in the range 1-100: ";
     cin >> number;

     while (number < 1 || number > 100)
       {
          cout << "ERROR: Enter a value in the range 1-100: ";
         cin >> number;
      }
     cout << "The number entered was:" << number << endl ;
     return 0 ;

 }
We can use loops for validation of an input number as shown in the above program.

Exercise:

1) Write an input validation loop that asks the user to enter 'Y','y',N or n .
File: ex_wh1.cpp

#include <iostream>
using namespace std;

int main()
{
       char x1 ;
       //TO DO


       return 0 ;
}

Do While Loops

The do while loop is similar to the while loop except it executes the statement first ( at least once ) and then checks the condition.
   do

    statement ;

  while ( expression );

  If the expression is false then we exit.

File: do1.cpp
#include <iostream>
using namespace std;

int main()  
{  
    int  number = 0   ;  
    do       
    {     
      cout << "Enter a value in the range 1-100: " ;
      cin >> number; 
    }  while (number < 1 || number > 100) ;

    cout << "The number entered was:" << number << endl ;
 return 0 ;  

}
Exercises

File: ex_do1.cpp
#include <iostream>
using namespace std;

int main()
{
  int count = 10;
  do
  {
    cout << "Hello World\n";
    count++;
  } while (count < 1);


}

File: ex_do2.cpp
#include <iostream>
using namespace std;

int main()
{
   int v1 = 10;
   do
    cout << v1 << endl ;
   while (v1 < 5);


}

File: ex_do3.cpp
#include <iostream>
using namespace std;

int main()
{
  int count = 0, number = 0, limit = 4;

 do
 {
    number += 2;
    count++;
 } while (count < limit);

 cout << "number:" << number << " count:" << count << endl;


}

For Loops

The for loop has the following syntax:
for ( initialization; test; update )

    statement;

The initialization happens first and only once. Then the test condition is tested and if true then the statement is executed and then the update statement happens. After that the test condition is evaluated and if true the whole sequence repeats. The for loop is useful when we want to iterate based on integer values.
File: for1.cpp
#include <iostream>
using namespace std;
int main()
{
    int  number = 0   ;
    cout << "Enter a number between 1 to 10." ;
    cin >> number ;
    for( int i1=0 ; i1 < number ; i1++ )
     {
         cout << "Hello" << endl  ;
     }

     return 0 ;
}
As usual there are many ways of coding to accomplish the same logic in programming.
File: for2.cpp
#include <iostream>
using namespace std;

int main()
{
    int  number = 0   ;
    cout << "Enter a number between 1 to 10." ;
    cin >> number ;
    for(  ;  number > 0  ;  number-- )
    {
        cout << "Hello" << endl  ;
    }
    return 0 ;
}
In the above we have left the initialization part of the for statement blank. In fact all the 3 parts can be blank. Notice the variable "number" is not defined in the for loop but outside it.
File: for3.cpp
#include <iostream>
using namespace std;

int main()
{
    for(  ;    ;   )
      {
          cout << "Hello" << endl  ;
       }
       return 0 ;
}
The above is an example of a for loop with all 3 sections as blank leading to an infinte loop.

Scope
It is possible to use 2 variables with the same name in a function as long as the variables are in different scope. In a for loop a variable can declare a variable in the initialization part. It's scope is valid to what's ever in the for loop block.
File: for4.cpp

#include <iostream>
using namespace std ;

int main()
{
    for( int i1=0 ; i1 < 10 ; i1++ ) //A
       {
            for(int i1=1 ; i1<5 ;   i1++ )          //B
            {
                cout << "i1:" << i1 << endl ;
            }   //C
      }    //D
     return(0) ;

}
Now we are going to remove the declaration of the inner i1.

The outer loop goes from 0 to 9 as before. Now let's see what
happens when i1 is 0 . The nested for loop starts and
initializes i1 with 1 and loops from 1 to 4 and comes
out when i1 is is 5 . Now the update statement

of the outer for loop is executed and i1 is 6 . Now we
come to the test condition of the outer for loop:

i1 < 10

and since 6 is less than 10 we enter the inner for loop
where i1 is again reset to 1 . We can see that the program
will keep running forever and print 1 to 4 and
repeat the sequence.


File: for5.cpp
#include <iostream>
using namespace std ;

int main()
{
      for( int i1=0 ; i1 < 10 ; i1++ )
      {
          for( i1=1 ; i1<5 ;   i1++ )
          {
              cout << "i1:" << i1 << endl ;
           }
       }
       return(0) ;
}

Fibonacci Sequence

The Fibonacci sequence starts with 2 numbers of 1 and 1. The
3rd number is computed by summing the 1st and 2nd number to
give us the number 2 . To get the nth number we simply add the
previous 2 numbers .

First few numbers of the Fibonacci sequence .

1 1 2 3 5 8 13 21  34

The below program uses loops to print the Fibonacci sequence .


File: fib1.cpp
#include <iostream>
using namespace std;

int main()
{
    int x1 = 1 , x2 = 1 ;
    int temp ;
    cout << x1 << endl ;
    cout << x2 << endl ;

    for( int i1=0 ; i1<10 ; i1++ )
    {
        cout << ( x1 + x2 ) << endl ;
        temp = x1 + x2 ;
        x1 = x2 ;
        x2 = temp ;
    }
        return 0;
}

Break and Continue

We have 2 keywords "break" and continue" that apply to only loops. The "break" breaks out of the loop and control falls to outside the loop.
File: br1.cpp
#include <iostream>
using namespace std;

int main()
{
        for( int i1=0  ; i1<10   ; i1++  )
        {
            if( i1 == 3 )
              break ;
            cout << i1 << endl  ;
        }
       return 0 ;
}
$ g++ br1.cpp ; ./a.exe
0
1
2
The "continue" keyword skips the rest of the body in the for loop and continues as if the body was executed to the next place in the code.
File: br2.cpp
#include <iostream>
using namespace std;
int main()
 {
     for( int i1=0  ; i1< 5   ; i1++  )
     {
         if( i1 == 3 )
          continue ;
         cout << i1 << endl  ;
      }
      return 0 ;

}
Output:

$ g++ br2.cpp ; ./a.exe
0
1
2
4
The variable i1 is getting incremented and will attain the value of 3 and then the continue is encountered and the cout will be skipped but the update statement i1++ will be executed and control moves as before.

Exercises



1)
File: ex1.cpp
#include <iostream>
using namespace std;

int main()
{
   {
      int   x = 2;
      int   y = x++;
      cout << x << y  << endl ;
   }
   {
     int  x = 2 ;
     int  y = ++x ;
     cout << x << y   << endl ;
   }
   {
       int x = 2 ;
       int y = 4 ;
        cout << x++ << --y   << endl ;
   }
   {
     int  x = 2  ;
     int  y = 2 * x++  ;
     cout << x << y  << endl  ;
   }
   {
      int  x = 99;
      if (x++ < 100)
        cout << "It is true!\n"  << endl ;
      else
        cout << "It is false!\n"  << endl ;
    }
    {
       int  x = 0 ;
       if (++x)
           cout << "It is true!\n"  << endl ;
       else
           cout << "It is false!\n"  << endl ;

    }

}


2)
File: ex2.cpp
#include <iostream>
using namespace std;

int main()
{
        for( int j1=0  ; j1< 5   ; j1++  )
             {
                   if ( j1 == 1 )
                       break ;
                   for( int i1=0  ; i1< 5   ; i1++  )
                    {
                         if( i1 == 3 )
                            break ;
                           cout << i1 << endl  ;
                     }
             }
      return 0 ;

}



3)
File: ex3.cpp
#include <iostream>
using namespace std;

int main()
{
     for( int j1=0  ; j1< 5   ; j1++  )
         {
              if ( j1 > 1 )
                 continue ;
              for( int i1=0  ; i1< j1   ; i1++  )
               {
                    if( i1 == 3 )
                        break ;
                       cout << i1 << endl  ;
                }
         }
       return 0 ;

}


4)
File: ex4.cpp
#include <iostream>
using namespace std;

int main()
 {
  for( int j1=0  ; j1< 5   ; j1++  )
      {
         for( int i1=0  ; i1< j1   ; i1++  )
            {
                    if( i1 == 1 )
                      break ;
                    cout << i1 << endl  ;
            }
      }
     return 0 ;

}

Solutions

1) File: ex1s.cpp
1) File: ex2s.cpp