Controlling flow within a loop statement


We’ve seen a few ways of looping within a program. There are a few occasions when you might want to break out of a loop when some particular condition occurs. Or in other words you may not want to go through the all the iterations within a ‘for loop’. Or you may want to break out of the loop for just one particular value of the loop variable. C++ provides a mechanism to break from loops using the ‘break’ and ‘continue’ statements. These are also called as ‘jump statements’. The following topics are covered in this section:


Break

We’ve already seen the use of the ‘break’ statement in the ‘switch…case’ construct. A ‘break’ statement can also be used to terminate (or break out) from a loop (like the ‘for’ and ‘while’ loops). Suppose you are using nested loops, then a ‘break’ specified in the body of the inner loop will lead to breaking out from the inner loop alone.

      #include<iostream.h>
      #include<stdlib.h>
      int main ( )
      {
          int x, i;
          for (i = 0; i<15; i++)
          {
               x = rand( );
               if (x>500)
               {
                  cout<<"\n Iteration number "<<i<<" random value is : "<<x; cout<<"\n\n exceeded 100 in iteration number "<<i;
                  cout<<"\n Breaking out from loop";
                  break;
               }
              cout<<"\n Iteration number "<<i<<" Random value is : "<<x;
          }
      return 0;
      }

First of all, in the above program the library function rand( ) has been used. This function is defined in the header file stdlib.h. rand ( ) is used for generating random numbers.

Can you find out what’s the logic of the above program? The ‘for’ loop is supposed to run 15 times. But within the ‘for’ loop we’ve specified a condition wherein if the random value generated exceeds 500 the program will break out of the ‘for’ loop.

The output for the program will be:


Continue

Sometimes you may not want to break out of a loop permanently. You may want to abort one particular iteration and then continue with the remaining iterations. For this purpose, the ‘continue’ statement is used. Let’s suppose that you have a ‘for’ loop with a loop variable named ‘j’ and you want the loop to run 10 times except for the value of j=5. In other words, you want the loop to run with all ‘j’ values except the value of 5. Hence, when the compiler enters the loop with the ‘j’ value of 5, the loop should terminate temporarily and then continue with the next ‘j’ value.

Consider a simple example:

      int main ( )
      {
           int j;
           for (j=1; j<8; j++)
          {
                 if (j= =5)
                {
                    continue;
                }
          cout<<"\n This is Round "<<j;
          }
          return 0;
      }

The output would be:

Notice that "This is Round 5" is not displayed because that iteration was not performed.

Remember: ‘Break’ is used to terminate permanently from a loop whereas ‘continue’ is used to terminate only a particular iteration.


Go To

To use the ‘goto’ statement you should use ‘labels’. We’ll start with an example:

      #include <iostream.h>
      int main ( )
      {
           int i;
           i = 1;
          LOOP : if (i<10)
                      {
                            cout<<i;
                            i=i+1;
                            goto LOOP;
                      }
            return 0;
      }

The above program will display the following:

123456789

LOOP is a label. When the compiler encounters goto LOOP, it will go to the label named LOOP and continue executing from there. The logic of the program should be easy to comprehend. The above program can be easily written using a ‘for’ loop.

A few beginners use the ‘goto’ statement excessively instead of using the other looping options available. Of course there’s nothing wrong with goto but it could lead to confusion when you start using many ‘goto’s in your program. It is advisable and good programming practice to avoid the use of ‘goto’ statements (unless it is really needed).

Beware of jumping initializations using GOTO:

Check out the following code, which makes use of the goto statement:

      #include <iostream.h>
      int main( )
      {
           char ans;
           cout<<"Enter y/n : ";
           cin>>ans;
           if (ans=='n')
          {
                goto done;
          }
          int x=5;                 //ERROR
          done:
                 cout<<x;
                 return 0;
      }

In C++, a variable can be declared and initialized anywhere in the C++ code. You can even declare and initialize a variable just before the statement return 0;. But the above program will lead to an error in compilation. Why? In C++, the goto statement should not jump (or skip) a declaration and initialization.

So, if you replace int x=5; by

the compiler will accept the program.

Try it: Try the above program with the modification and give an input of ‘n’ and see what happens. The result will be some weird answer and NOT 5 because the goto statement will bypass the initialization of the variable ‘x’ and hence you get an ambiguous answer. Be very careful when using ‘goto’ in your program.


Return

The ‘return’ statement will be covered while discussing about functions. When using any looping technique within a function, the return statement can be used to break out from the loop and return control to the caller. We shall look at this later. For the time being just remember that the ‘return’ statement can be used to break out from a loop.


Apply the techniques

Let’s write a program that covers most of the techniques that we’ve learnt.

Problem: Write a program in C++ to obtain a date from the user. The user will enter the date in the format: dd/mm/yyyy. Our program should print the corresponding month and also the number of days in that particular month. The program should also inform the user as to whether the year is a leap year or not. For example if the user enters: 11 10 1980 then the display should be:

Solution:

  1. First obtain the inputs in three different variables (i.e. the day, month and year).
  2. Write a ‘switch case’ statement to check for the month.
  3. Within the case statements print the month and also set some other variable to the number of days present in that month.
  4. Outside the ‘switch case’ block, print the date.
  5. Using an ‘if’ condition check whether the year is divisible by 4 (which means it is a leap year).

      #include <iostream.h>
      int main( )
      {
          int d,m,y,days;
          cout<<"\nEnter the Date (DD MM YYYY): ";
          cin>>d>>m>>y;
          switch(m)                  //To print the month
          {
              case 1:
                      cout<<"\nJanuary";
                      days=31;
                      break;
              case 2:
                      cout<<"\nFebruary";
                      break;
              case 3:
                      cout<<"\nMarch";
                     days=31;
                     break;
             //…write the remaining cases
              case 11:
                     cout<<"\nNovember";
                     days=30;
                     break;
              case 12:
                     cout<<"\nDecember";
                     days=31;
                     break;
             default:
                     cout<<"\nInvalid month";
                     return 0;                          //quit the program!
                     break;
            }
          cout<<" "<<d<<","<<y<<".";        //display the date.
          if (m==2)                                     //February could be 28/29 days
          {
                if(y%4==0)
               {
                     days=29;
               }
               else
              {
                    days=28;
               }
           }
          cout<<"This month has "<<days<<" days.";   //display number of days in the month
          if (y%4==0) //check whether it is a leap year
          {
                 cout<<" This is a leap year.";
          }
          else
         {
                cout<<" This is not a leap year.";
          }
          return 0;
      }

A leap year is actually a year that is divisible by 4 and not by 100 or a year that is divisible by 400. You can add these two conditions in the above program. More questions are given in the exercise section for this chapter.


Recap


Go back to the Contents Page


Copyright © 2004 Sethu Subramanian All rights reserved.