Navigation



5.5 — While statements

The while statement is the simplest of the three loops that C++ provides. It’s definition is very similar to that of an if statement:

while (expression)
    statement;

A while statement is declared using the while keyword. When a while statement is executed, the expression is evaluated. If the expression evaluates to true (non-zero), the statement executes.

However, unlike an if statement, once the statement has finished executing, control returns to the top of the while statement and the process is repeated.

Let’s take a look at a simple while loop. The following program prints all the numbers from 0 and 9:

int iii = 0;
while (iii < 10)
    {
    cout << iii << " ";
    iii++;
    }
cout << "done!";

This outputs:

0 1 2 3 4 5 6 7 8 9 done!

iii is initialized to 0. 0 < 10 evaluates to true, so the statement block executes. The first statement prints 0, and the second increments iii to 1. Control then returns back to the top of the while statement. 1 < 10 evaluates to true, so the code block is executed again. The code block will repeatedly execute until iii == 10, at which point 10 < 10 will evaluate to false, and the loop will exit.

It is possible that a while statement executes 0 times. Consider the following program:

int iii = 15;
while (iii < 10)
    {
    cout << iii << " ";
    i++;
    }
cout << "done!";

The condition 15 < 10 evaluates to false, so the while statement is skipped. The only thing this program prints is done!.

On the other hand, if the expression always evaluates to true, the while loop will execute forever. This is called an infinite loop. Here is an example of an infinite loop:

int iii = 0;
while (iii < 10)
    cout << iii << " ";

Because iii is never incremented in this program, iii < 10 will always be true. Consequently, the loop will never terminate, and the program will hang. We can declare an intentional infinite loop like this:

while (1)
{
  // this loop will execute forever
}

The only way to exit an infinite loop is through a return statement, a break statement, an exception being thrown, or the user killing the program.

Often, we want a loop to execute a certain number of times. To do this, it is common to use a loop variable. A loop variable is an integer variable that is declared for the sole purpose of counting how many times a loop has executed. Loop variables are often given simple names, such as i, j, or k. Hungarian Notation is often ignored for loop variables (though whether it should be is another question altogether).

However, naming variables i, j, or k has one major problem. If you want to know where in your program a loop variable is used, and you use the search function on i, j, or k, the search function will return half your program! Many words have an i, j, or k in them. Consequently, a better idea is to use iii, jjj, or kkk as your loop variable names. Because these names are more unique, this makes searching for loop variables much easier, and helps them stand out as loop variables. An even better idea is to use "real" variable names, such as nCount, nLoop, or a name that gives more detail about what you're counting.

Each time a loop executes, it is called an iteration. Often, we want to do something every n iterations, such as print a newline. To have something happen every n interations, we can use the modulus operator:

// Loop through every number between 1 and 50
int iii = 1;
while (iii <= 50)
{
    // print the number
    cout << iii << " ";

    // if the loop variable is divisible by 10, print a newline
    if (iii % 10 == 0)
        cout << endl;

    // increment the loop counter
    iii++;
}

This program produces the result:

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50

It is also possible to nest loops inside of other loops. In the following example, the inner loop and outer loops each have their own counters. However, note that the loop expression for the inner loop makes use of the outer loop's counter as well!

// Loop between 1 and 5
int iii=1;
while (iii<=5)
{
    // loop between 1 and iii
    int jjj = 1;
    while (jjj <= iii)
        cout << jjj++;

    // print a newline at the end of each row
    cout << endl;
    iii++;
}

This program prints:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Quiz

1) In the above program, why is jjj declared inside the while block instead of following immediately following the declaration of iii?

2) Write a program that prints out the letters a-z along with their ASCII codes. Hint: to print characters as integers, you have to use a static_cast.

Quiz Answers

1) Show Solution

2) Show Solution

5.6 -- Do while statements
Index
5.4 -- Goto statements

45 comments to 5.5 — While statements

  • Allen01

    In the code above, shouldn’t the if statement read:

     if (iii % 10 == 0)  

    [ Yes, it should. Thanks for catching that. -Alex ]

  • Cameron

    Why does the last program print

    1
    1 2
    1 2 3
    1 2 3 4
    1 2 3 4 5

    Instead of

    1
    2
    3
    4
    5

    ? Am I missing something? It seems to only print one number each time it repeats by looking at the code.

    • This happens because there is a loop inside of a loop.

      The outer loop iterates iii from 1 to 5. The inner loop iterates jjj from 1 to iii.

      Each time the outer loop iterates, all of the inner loop iterations are restarted.

      So the first time, iii = 1 and jjj = 1. The inner loop executes once and prints 1.
      The second iteration, iii = 2 and jjj = 1. The inner loop executes twice and prints 1 2.
      The third iteration, iii=3 and jjj = 1. The inner loop executes three times and prints 1 2 3.
      And so on.

  • [...] 2007 Prev/Next Posts « 5.3 — Switch statements | Home | 5.5 — While statements » Thursday, June 21st, 2007 at 6:55 [...]

  • how do i revert the last program?
    that will print
    * * * * *
    * * * *
    * * *
    * *
    *
    please answer my question asap...
    thanks...
    • Noha
       int iii=5;
      	while (iii>=0)
      	{
      		// loop between 1 and iii
      		int jjj = 1;
      		while (jjj <= iii)
      		{
      			cout << "*" ;
      			jjj++;
      		}
      
      		// print a newline at the end of each row
      		cout << endl;
      		iii--;
      	}

      notice what i changed in the given example…

    • Canute
      I don't know I'm sure this is way late but here if this helps.
      
      
      // Loop between 1 and 5
      int iii=1;
      while (iii<=5)
      {
          // loop between 1 and iii
          int jjj = 5;//I flipped 1 to 5 so it starts from bottom up
          while (jjj >= iii)// Flipped <= to >=, if not it would not loop
              cout << jjj--;//Flipped the minus to so it gets smaller, if not it would be infinite
      
          // print a newline at the end of each row
          cout << endl;
          iii++;
      }
      
  • Hero Doug

    Even though it’ll never be executed, there is a slight bug in the code from the second example.

    i++ should be iii++

    int iii = 15;
    while (iii < 10)
        {
        cout << iii << " ";
        i++
        }
    cout << "done!";
    
  • Mohamad

    I rerote the code from the first example to request an integer from the user and then add each number to the next number on the row and give the combined sum of the row.

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    
    int iii=1;
    int holder2;
    cout << "Enter the number you want to add up to: ";
    int iterations;
    cin >> iterations;
        // loop between iii and iterations
    while (iii<=iterations)    //while iii is less than or equal to iterations do the following:
    {
        // loop between 1 and iii-1
        int jjj = 1;
        int holder;
        int total=0;
        int finaltotal=0;
        while (jjj < iii)
        {
            holder=jjj;
            total=total + holder;
            cout << holder << " + ";
            jjj++;                  //increment jjj by 1
        }
    
            holder2=total;
            finaltotal=holder2+jjj;
            cout << jjj;
            cout << " = " << finaltotal;
    
        // print a newline at the end of each row
        cout << endl;
        iii++;
    }
    
    return(0);
    }
     

    The resulting output for 5 iterations is:
    Enter the number you want to add up to: 5
    1 = 1
    1 + 2 = 3
    1 + 2 + 3 = 6
    1 + 2 + 3 + 4 = 10
    1 + 2 + 3 + 4 + 5 = 15

    Not sure but If I’m right, but I think this is a fibonacci sequence. (please correct me if I’m wrong)
    It took a while to figure out the logic (and I sure this is probably not the most efficient solution, but it works)… sorry for the lack of comments… I’m gonna go back and comment more. Great Tutorial… I finally feel like I’m getting somewhere.

  • CSESTUDENT
    #include<iostream>
    int main()
    {
        using namespace std;
        char chValue=97;
        while (chValue<=122)
        {    cout << static_cast<char>(chValue) << " " << static_cast<int>(chValue) << endl;
             chValue=chValue++;
        }
    }
    

    Is it acceptable to write the quiz question in this way?

    • Quinn

      It’s acceptable and will compile, but for readability it’s a bit ambiguous. It may not be plainly obvious what is meant by 97 and 122.

      I also believe static_cast<char>(chValue) is unnecessary, it should just be chValue.

  • Matthew

    Instead of doing:

    static_cast<int>(chValue)

    I did:

    (int)chValue

    It compiled and worked fine. It seems easier than the static_cast code. Is that bad coding/is there a reason why it shouldn’t be done like that?

    Thanks

    • Quinn

      (int)chValue is a C-style cast, whereas static_cast<int>(chvalue) is a C++ style one, and they are different in the fact that C-style casts are less type safe than C++ ones. Because of this, it is always suggested that you do, and get into the habit of doing, static_cast instead of C-style casts. Alex talked about this in lesson 4.4.

  • iammfa

    There is error in code number 2 line 5:
    i++; it must be iii++;

  • fero45

    For conversion from letter to ASCII and back I used this and it worked:

    char ch = ‘d’
    cout << ch << " " << int(ch) << endl;

    int c = 100;
    cout << c << " " << char(c) << endl;

    Is there anything wrong in this int(char) / char(int) so that we have to use static_cast(char) ?

    Fero

  • Fluke

    In the solution 2 answer:
    jjj is declared inside the while block so that it is recreated (and reinitialized to 1) each time the outer loop executes. If jjj were declared before the outer while loop, it’s value would never be reset to 1, or we’d have to do it with an assignment statement. Furthermore, because jjj is only used inside the outer while loop block, it makes sense to declare it there. Remember, declare your variables in the smallest scope possible!

    It is okay if we follow – variables inside the scope.
    But isnt it more work for the PC to recreate jjj variable each loot (for example, if our other loop was like 10 000 times long) instead of having the jjj once declared outside and jjj = 1 inside?

  • Radek

    Don’t forget that infinite loops like

    while(true) {
    
    }
    

    is usually used in web servers!

  • output should b
    1
    123
    12345
    1234567

  • polabonez

    I really just wanted to create an account, log in, just to post a thank you for this all. I have been attempting to teach myself as with a full time job I don’t have time to go to school. I have a lot to learn, but just the detail you have gone into so far has been amazing.

    Thank again.

  • Barbarababy

    Hi Alex, I have a problem with my assignment. Can you help me, please? Here is the assignment:

    Write a program that will analyze the data from a physics experiment.
    The data consists of a series of position measurements for a moving object. The position measurements will be entered by the user of the program as they are continually prompted. Each of the position measurements that the user enters will have been recorded at uniform time intervals. This time interval will be entered by the user when the program begins and will be followed by the series of position measurements. Each position should be greater than or equal to the previous position because the object is either moving in one direction or still, but never moving backwards. Therefore a negative position measurement will be used to signal the end of the user’s data for the run of the program.
    After each of the position measurements has been entered, calculate and display the following:
    1. the average velocity for the time interval
    2. the average acceleration for the time interval
    Calculations
    Use the following formulas for the calculations:
    change of position = current position – previous position

    change of velocity = current velocity – previous velocity

    average velocity = change of position / time interval

    average acceleration = change of velocity / time interval
    Notes
    1. The starting position and starting velocity should both be 0.
    2. There should be a loop to validate the position entered by the user. As stated earlier, each position that the user enters must be greater than or equal to the previous position. Each time the user enters an invalid position, an error message that includes the invalid position as well as the previous valid position should be displayed and the user should be given a chance to enter the current position again.
    Processing Requirements
    1. At the top of the C++ source code, include a documentation box that resembles the ones from programs 1 and 2.
    2. The program should be fully documented.
    3. Use meaningful variable names.
    4. Make sure and test the program with values other than the ones in the Sample Output.
    5. Hand in a copy of the source code using Blackboard.
    Sample Output
    Motion Analysis

    Enter the uniform time interval in seconds: 2.5

    Enter a position in feet (negative value to quit): 2

    Average velocity (this interval): 0.80 feet/second
    Average acceleration: 0.32 feet/second/second

    Enter a position in feet (negative value to quit): 5

    Average velocity (this interval): 1.20 feet/second
    Average acceleration: 0.16 feet/second/second

    Enter a position in feet (negative value to quit): 4

    Invalid value: 4 is less than the current position of 5. Try again.

    Enter a position in feet (negative value to quit): 12

    Average velocity (this interval): 2.80 feet/second
    Average acceleration: 0.64 feet/second/second

    Enter a position in feet (negative value to quit): -1

    Thank you very much!

  • Barbarababy

    I have tried the following, what’s wrong in it?

    # include
    # include

    using namespace std;

    int main()
    {
    double prev_pos = 0;
    double current_pos,
    change_pos;
    double prev_vel = 0;
    double current_vel,
    change_vel,
    time_int,
    avg_vel,
    avg_acc;

    change_pos = current_pos – prev_pos;
    change_vel = current_vel – prev_vel;
    current_vel = avg_vel – prev_vel;
    avg_vel = change_pos / time_int;
    avg_acc = change_vel / time_int;

    cout << "Motion Analysis" << endl;
    cout << endl;

    // ask the user to enter a time interval in second

    cout <> time_int;
    cout << endl;
    cout <= 0 )
    {
    cout <> current_pos;
    cout << endl;
    cout << "Average velocity (this interval): "
    << avg_vel << " feet/second" << endl;
    cout << endl;
    cout << "Average Acceleration: "
    << avg_acc << " feet/second/second" << endl << endl;

    if ( current_pos < prev_pos )
    {
    cout << "Invalid value: " << current_pos;
    cout << " is less than the current position of " << current_pos;
    cout << ". Try again.";
    cout << endl << endl;
    }
    else
    {
    cout << current_pos;
    cout << endl << endl;
    }
    }

    cout << endl;
    system ("pause");
    return 0;

  • kakatu

    I have a problem with my assignment. Can you help me, please?
    Here is the assignment:
    to make telephone numbers easier to remember, some companies use letters to show their telephone number.for example using letters,the telephone number 438-5626 can be shown as GET LOAN.in some cases, to make a telephone number meaningful, companies might use more than seven letters. for example,225-5466 can be displayed as CALL HOME, which uses 8 letters. write a program that prompts the user to enter a telephone number expressed in letters and output the corresponding telephone number in digits. if the user enter more than seven letters then process only the first seven letters. also output the -(hyphen) after the third digit. allow the user to use both uppercase and lowercase letters as well as spaces between word.moreover, your program should process a many telephone numbers as the user wants. (the program must use while statement)

  • mac

    what is the input of this one and also the reverse, using the for loop ,pls help asap
    *
    **
    ***
    ****
    *****

  • mac

    from left to right up, and also downwards…..

  • JustACPlusPluser

    I posted the following code into MS Visual C++ 2010 Express:

    #include “stdafx.h”
    #include
    #include “stdafx.h”
    using namespace std;

    int iii = 3;
    while (iii < 10)
    {
    cout << iii << " ";
    iii++;
    }
    cout << "done!";

    And the while statement says it "expected a declaration", plus when I try to compile, it gives me a bunch of errors about a missing semicolon. Please help ASAP,

    James

    • omril

      Did you leave out all the necessities to spare room ?

      if you didn’t to compile it you’ll need to paste:

      #include “stdafx.h” // for MS visual Studio
      #include

      int main()
      {

      using namespace std;

      int iii = 3;
      while (iii < 10)
      {
      cout << iii << " ";
      iii++;
      }
      cout << "done!";
      }

  • gel24

    what is the input of this one . can you help me please ? :(

    Enter starting number: 5
    How many number to display: 4
    Output:
    5 = 25
    6 = 36
    7 = 49
    8 = 64

  • ballubhai

    I found very useful site.
    I commend for them.

  • ghrte

    Hello , i have a question

    If i have:

    int randnum;
    do{

    randnum=rand()%(2+1)-1;
    } while (randnum==0);

    i am receiving 1 or -1.
    Lets say that the randnum takes the value 1.The loop will continue until the randnum takes the value 0 and then stops.But i am receiving value 1 and not 0 . I mean , the loop must stop when randnum takes value 0.The value of randnum that it returns isn’t the 0 but it is the last value before it goes to 0?

    Thanks!

  • mks

    first i want to thank for this awesome tutorial
    i tried this code
    #include
    using namespace std;
    int main()
    {
    int iii=1;
    while(iii<4)
    {
    int jjj=1;
    while(jjj<iii)
    {
    cout<<jjj++;
    }

    iii++;
    }
    return 0;
    }
    i thought the output is 1
    12
    123
    but it shows
    1
    12
    wats the wrong can somebody explain

    • nishido

      You would need


      while(jjj<=iii)...

      notice the extra equals. Just using less than stops before the value of iii. So in your code you have, while jjj is between 1 and 2 inclusive (i.e. less than iii which equals a max of 3), print jjj.

  • 1234H

    How do I adjust this code so it skips 1763 and the console window outputs seven, sevens?
    7777777

    It keeps outputting 7779540 which means it is not avoiding the number 1763 like it should.

    Thanks

    CODE

    #include
    using namespace std;

    int main()
    {
    int L=1, sumg=0;
    while (L<=3944)
    {
    sumg = sumg + L; L++;

    if (L==1763)
    {
    continue;
    }
    }
    cout << sumg << endl;
    return 0;
    }

  • nishido

    So I tried to solve Euler’s problem #1 (calculate the sum of all multiples of 3 or 5 below 1000) using a while statement, but for some reason there’s a problem with a local variable. Here’s my code:


    int sumOfMultiples(int limit)
    {
    int sum;
    int iii=0;
    while (iii<=limit)
    {
    if (iii % 3 == 0 || iii % 5 == 0)
    {
    sum += iii;
    }
    iii++;
    }

    return sum;
    }

    I keep getting an error when I try to run, saying sum isn’t initialized. When it is. It’s initialized outside the if and while blocks, so it should still carry into those blocks shouldn’t it? If I declare sum as “static int sum” then it works, but I don’t see why it doesn’t work otherwise.

  • Littlem

    I also inverted the inverted loop to make it count down from 5 to 1.

    using namespace std;

    int main()
    {
    int iii=5;
    while(iii>=1)
    {
    int jjj=iii;
    while(jjj>=1)
    cout<<jjj–<<" ";

    cout<<endl;
    iii–;
    }

    return 0;
    }

    This outputs the following:

    5 4 3 2 1
    4 3 2 1
    3 2 1
    2 1
    1

  • Littlem

    in the code above, jjj has double negative signs and iii also has double negative signs.

  • pranesh

    the following code prints like:
    98 a
    99 b
    .
    .
    .
    .
    123 z
    what is the problem with the code, please answer?

    int main()
    {

    int iii = 97;
    while (iii <= 122)
    {
    cout << iii << "t" << (char)iii++ << endl;

    }

    return 0;

    }

  • Leolas

    Hi! this is how i made the question 2, i think that is very similar, but i used the correspondent ASCII code instead of the letter; however, it prints the same thing.
    #include

    int main()
    {
    using namespace std;

    char chValue = ‘a’;
    while (chValue <= 'z')
    {
    cout << chValue << " " << static_cast(chValue) << endl;
    chValue++;
    }
    }

You must be logged in to post a comment.