Activity 7-3 -  for Statement (for loop)



You may remember when we introduced while loops, we mentioned that a good loop must have at least three things to work correctly: 1) the controlling variable must be initialized, 2) the Boolean expression must be valid and include the controlling variable, and 3) the controlling variable must be updated in the body of the loop.  A for loop has all three of these between ( and ), here is how:

for(initilization_Action; Boolean_Expression; Update_Action)
{
      Statement_1
      Statement_2
        ...
        ...
      Statement_last
}

The following program uses for loops to draw a rectangle of desired size.

// P73.cpp - This program draws a rectangle n rows and m columns.
// The program asks the user to input a character for drawing the rectangle

#include<iostream>
using namespace std;

int main( )
{
     int rows, columns;
     char draw_char;

     cout << "Enter number of rows and columns \n";
     cin >> rows >> columns;

     cout << "Enter the character to draw with \n";
     cin >> draw_char;

     for(int i = 0; i < rows; i++)
     {
            for(int j = columns; j > 0; j--)
            {
                  cout << draw_char;
             }
             cout << endl;
      }

      return 0;
}

As you can see in the above example, we have used two for loops one within the other.  Such use of loops is known as nested loops.  The loop inside is said to be faster because for every row, i, j will change columns times.

The following program will display the days for a month of the year.  The input to the program is the number of days and the day of the week on which the first day of the month falls.

The following program uses for loops to draw a rectangle of desired size.

// P73a.cpp - This program displays the days of a month
// Day 0 : Sunday, Day 1: Monday, Day 2: Tuesday
// Day 3: Wednesday, Day 4: Thursday, Day 5: Friday
// Day 6: Saturday

#include<iostream>
#include<cmath>
using namespace std;

int main( )
{
     int n_days, start_day;

     cout << "Enter the number of days, 28, 29, 30 or 31 \n";
     cin >> n_days;

     cout << "Enter the first day of the month \n";
     cin >> start_day;

      cout << "Sun\tMon\tTue\tWed\tThr\tFri\tSat\n";
     for(int i = 0; i < start_day; i++)
     {
            cout << " \t";
     }
     for(int j = 1; j <= n_days; j++)
     {
           if( j%7 == 0)
               cout << endl;

            cout << j  << "\t";
     }
     cout << endl;
     return 0;
}

Exercise 7.4
Modify the above program such that it uses a function called display_month(int n_days, int start_day) to display the days of a month.  Call your new program ex74.cpp.  In the new program, replace the following segment:

     for(int i = 0; i < start_day; i++)
     {
            cout << " \t";
     }

with a function, get_tabs(int start_day), that uses a switch statement with start_day as its Controlling_Expression to display the correct number of tabs.