Share
C++ Programming

Course Outline

Week 1
Week 2
Week 3
Week 4

LOOPING CONTROLS

  • The While statement
  • The Do … while statement
  • The for statement
  • The continue and break statement
  • Nested loops

SponsoredAdvertise

Explanations to week content

The While Statement

 

Branch statements allow you to direct the flow of a program’s execution down one path or

another.

 

The simplest form of looping statement is the while loop.Here’s what the while loop looks like:

while(condition)

{

// ...repeatedly executed as long as condition is true

}

 

From the above state, the block of code in the while repeats over and over again until the condition in the while loop is false.

 

Example

 

Write a program that takes two numbers and output the minimum and maximum of the entered numbers. The program should repeat until a user decides to quit the program.

 

Solution

 

We will only add the loop concept to the program we wrote in week 3 for the minimum and maximum numbers.

 

#include<iostream>
 
using namespace std;
int main()
{
  float a,b,max;
  int exit = 0;
   cout << "Program to show the maximum number between two numbers."<<endl;
  while(exit!=1){
     cout << "Enter the first number"<<endl;
     cin >> a;
     cout << "Enter the second number"<<endl;
     cin >> b;
     max = (a>=b)?a:b;
     cout << "The maximum number is"<<max<<endl;
     cout << "Enter 1 to exit program or any other number to run again"<<endl;
     cin >> exit;
  }
return 0;
}

 

The condition for the while loop above (while(exit!=1)) is (exit!=1), thus exit is not equal to 1. The loop will stop when exit is 1. So far as the exit value is not 1, the block of code in the while loop will be repeated over and over again. Once a user enters 1, the condition will be false since exit is now 1 and the loop ends.

 

Write a program that prints out the numbers from 1 to 10 in

i)       Horizontal

ii)      Vertical

 

 

Solution

 

#include<iostream>
 
using namespace std;
int main()
{
  int i = 1;
  //In horizontal
  while(i<=10){
        cout<<i<<" ";
        i++;
  }
  // In vertical
  // Start a new line before the first number
  cout<<endl;
  i = 1;
  while(i<=10){
        cout<<i<<endl;
        i++;
  }
return 0;
}

 

The while loop will keep on repeating so far as the condition i<=10 is true. i needs to be initialized to make the condition true in order for the block of code in the while loop to start execution. The repetition ends when i<=10 is false. Thus when i is more than 10. i++; increases the i anytime that line of code is executed. i++; is the same as i = i+1;

 

Detail Explanation

 

Repetition Value of i Condition Boolean Loop Status
0 i = 1 1 <= 10 True While loop continues
1 i++; i = 2  same as i = 1+1 2 <= 10 True While loop continues
2 i++; i = 3  same as i = 2+1 3 <=10 True While loop continues
3 i++; i = 4 same as i = 3+1 4 <=10 True While loop continues
4 i++; i = 5 same as i = 4+1 5 <=10 True While loop continues
5 i++; i = 6 same as i = 5+1 6 <=10 True While loop continues
6 i++; i = 7 same as i = 6+1 7 <=10 True While loop continues
7 i++; i = 8 same as i = 7+1 8 <=10 True While loop continues
8 i++; i = 9 same as i = 8+1 9 <=10 True While loop continues
9 i++; i = 10 same as i = 9+1 10 <=10 True While loop continues
10 i++; i = 11 same as i = 10+1 11 <=10 False While loop then ends

 

In summary while loop is written in the form below:

 

//initialize the loop control variable(s). The expression must be true to start the loop.

while(expression)

{

.

.

.

//update the loop control variable(s). This will make the expression to be false at a point in time.

.

.

.

}

 

NOTE: If your loop control variable(s)update doesn’t make the expression false at certain point in time, you will end up with an endless loop.

 

 

The Do … while statement

 

A separate, less frequently used version of the while loop known as the do … while appears

identical except the condition isn’t tested until the bottom of the loop:

 

do

{

// ...the inside of the loop

} while (condition);

 

 

Because the condition isn’t tested until the end, the body of the do … while is always executed at

least once.Thus since the condition is tested at the bottom, the block of code in the do{}at least once before the condition is tested. If the condition is true, the loop continues and if not it is not repeated.

 

Example

 

#include<iostream>
 
using namespace std;
int main()
{
  int a = 2;
  int e = 10;
  do{
    cout<<a<<endl;
    a = e-a;
 }while(a>3);
return 0;
}

 

The syntax in the do{} will run even though which is 2 is less than 3. This is because the condition is only tested at the bottom.

 

The above code is therefore not the same as the while loop with the same syntax.

 

#include<iostream>
#include<math.h>
 
using namespace std;
int main()
{
  int a = 2;
  int e = 10;
  while(a>3){
    cout<<a<<endl;
    a = e-a;
  }
return 0;
}

 

The above code will not output anything because the condition is tested at the top. a which is 2 is less than 3 and so the condition is false, therefore the syntax in the while loop won’t be executed.

 

A do...while loop can be used for input validation. Suppose that a program prompts a user to enter a test score, which must be greater than or equal to 0 and less than or equal to 100. If the user enters a score less than 0 or greater than 100, the user should be prompted to re-enter the score. The following do...while loop can be used to accomplish this objective:


int score;
do
{
cout << "Enter a score between 0 and 100: ";
cin >> score;
cout << endl;
}
while (score< 0 || score > 100);

 

The for statement

 

The most common form of loop is the for loop. The for loop is preferred over the more basic

while loop because it’s generally easier to read (there’s really no other advantage).

The for loop has the following format:

for (initialization; conditional; increment or decrement)

{

// ...body of the loop

}

The for loop is equivalent to the following while loop:

 

initialization;

while(conditional)

{

// ...body of the loop

increment or decrement;

}

 

Examples

 

Write a program that takes an integer from the user and output the multiplication table for that user. For instance if a user enters 2, the output should look something like this:

 

1 x 2 = 2

2 x 2 = 4

3 x 2 = 6

4 x 2 = 8

5 x 2 = 10

6 x 2 = 12

7 x 2 = 14

8 x 2 = 16

9 x 2 = 18

10 x 2 = 20

11 x 2 = 22

12 x 2 = 24

 

Solution

 

#include<iostream>
 
using namespace std;
int main()
{
    int multiples;
    cout <<"Enter the integer number to generate the multiplication table"<<endl;
    cin>>multiples;
    cout <<"----------------------------------------"<<endl;
    cout <<"MULTIPLICATION TABLE FOR "<<multiples<<endl;
    cout <<"----------------------------------------"<<endl;
    for(inti=1;i<=12;i++){
        cout<<i<<" x "<<multiples<<" ="<<i*multiples<<endl;
    }
return 0;
}

 

The initialization is (int i=1). i is initialized to 1 because our loop starts from 1.

The termination condition is i<=12. The loop will end when i gets to 13 and the condition becomes false. The i++increases the value of i for each iteration.

 

You can use the do .. while to repeat the program as shown in the code below

 

#include<iostream>
using namespace std;
int main()
{
    float num;
    int exit = 0;
    do{
        cout<<"Enter the number"<<endl;
       cin>>num;
        for(inti=1;i<=12;i++){
           cout<<i<<" x "<<num<<" ="<<i*num<<endl;
        }
        cout <<"Enter 1 to exit program or any number continue"<<endl;
        cin >>exit;
    }while(exit!=1);
return 0;
}

 

Write a program which

i.     Prints out years starting from the current year to the past 100th year.

ii.    Prints out years starting from the past 100th year to the current year.

 

Solution

 

i.     Prints out years starting from the current year to the 100th year.

 

#include<iostream>
 
using namespace std;
int main()
{
    //Loop from the current to the last 100 year and output the result
    int last_100_year= 2019 - 100;
    for(int year=2019;year>=last_100_year;year--){//or for(int year=2019;year>=1919;year--)
        cout <<year<<endl;
    }
 
return 0;
}

 


ii.    Prints out years starting from the 100th year to the current year.

 

#include<iostream>
 
using namespace std;
int main()
{
    //Loop from the current to the last 100 year and output the result
    int current_year =2019;
    int last_100_year= current_year - 100;
    for(int year=last_100_year;year<=current_year;year++){//or for(int year=1919;year<=2019;year++)
        cout <<year<<endl;
    }
 
return 0;
}

 

 

The continue and break statement

 

When the break command is encountered, it causes control to exit the current loop immediately. The control passes from the break statement to the statement immediately following the closed brace at the end of the loop.

 

The format of the break commands is as follows:

while(condition) // break works equally well in for loop

{

if (condition)

{

break; // exit the loop

}

. // controlpasses here

. // controlpasses here

. // controlpasses here

}

// The control moves immediately here (after the closed brace at the end of the loop)

 

Example

 

Write a program that sum positive integers entered by a user continuously until a negative number is entered.

 

Solution

 

#include<iostream>
 
using namespacestd;
int main()
{
    int sum,number;
    sum = 0;
    while(true){
        cout << "Enter a positive integer"<<endl;
        cin>>number;
        if(number<0){
            break;
        }
        sum = sum+number;
    }
    cout <<"Sum:"<<sum<<endl;
 
return 0;
}


If negative number is entered the condition, (number<0) will be true and hence the break syntax will move the control pass the syntax sum = sum+number; to cout<<”sum:”<<sum<<endl;

 

 

Continue

 

The continue statement is used in while, for, and do. . .while structures. When the

continue statement is executed in a loop, it skips the remaining syntax in the loop and

proceeds with the next iteration of the loop.

 

Example

 

while(cin)
{
    if (num< 0)
    {
       cout<< "Negative number found in the data." << endl;
       cin>> num;
       continue;
    }
    sum = sum + num;
    cin >> num;
}

 

When the continue is executed, the sum = sum+num; cin>>num; is skipped and the loop is repeated.

 

Nested loops

 

A loop and another loop.

 

Example

 

Write a program that outputs the multiple table as shown below:

 

1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144

 

 

Solution

 

#include<iostream>
 
using namespace std;
int main()
{
    for(int i=1;i<=12;i++){
        for(int j=1;j<=12;j++){
            cout<<i*j<<"  ";
        }
       cout<<endl;
    }
return 0;
}

 

Assignment

 

Write a program that reads a set of integers and then finds and prints the sum

of the even and odd integers.

SponsoredAdvertise