Search

Admin

5.5 — While statements

The while statement is the simplest of the four loops that C++ provides, and it has a definition 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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

#include <iostream>

intmain()

{

intcount=0;

while(count<10)

{

std::cout<<count<<" ";

++count;

}

std::cout<<"done!";

return0;

}

This outputs:

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

Let’s take a closer look at what this program is doing. First, count is initialized to 0. 0 < 10 evaluates to true, so the statement block executes. The first statement prints 0, and the second increments count 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 count is 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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

#include <iostream>

intmain()

{

intcount=15;

while(count<10)

{

std::cout<<count<<" ";

++count;

}

std::cout<<"done!";

return0;

}

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

Infinite loops

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:

1

2

3

4

5

6

7

8

9

10

#include <iostream>

intmain()

{

intcount=0;

while(count<10)// this condition will never be false

std::cout<<count<<" ";// so this line will repeatedly execute

return0;// this line will never execute

}

Because count is never incremented in this program, count < 10 will always be true. Consequently, the loop will never terminate, and the program will print "0 0 0 0 0 ..." forever.

We can declare an intentional infinite loop like this:

1

2

3

4

while(1)// or while (true)

{

// this loop will execute forever

}

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

Programs that run until the user decides to stop them sometimes intentionally use an infinite loop along with a return, break, or exit statement to terminate the loop. It is common to see this kind of loop in web server applications, that run continuously and service web requests.

Loop variables

Often, we want a loop to execute a certain number of times. To do this, it is common to use a loop variable, often called a counter. A loop variable is an integer variable that is declared for the sole purpose of counting how many times a loop has executed. In the examples above, the variable count is a loop variable.

Loop variables are often given simple names, such as i, j, or k. 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 count, or a name that gives more detail about what you're counting.

It is best practice to use signed integers for loop variables. Using unsigned integers can lead to unexpected issues. Consider the following code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

#include <iostream>

intmain()

{

unsignedintcount=10;

// count from 10 down to 0

while(count>=0)

{

if(count==0)

std::cout<<"blastoff!";

else

std::cout<<count<<" ";

--count;

}

return0;

}

Take a look at the above example and see if you can spot the error. It's not very obvious.

It turns out, this program is an infinite loop. It starts out by printing "10 9 8 7 6 5 4 3 2 1 blastoff!" as desired, but then goes off the rails, and starts counting down from 4294967295. Why? Because the loop condition count >= 0 will never be false! When count is 0, 0 >= 0 is true. Then --count is executed, and count overflows back to 4294967295. And since 4294967295 is >= 0, the program continues. Because count is unsigned, it can never be negative, and because it can never be negative, the loop won't terminate.

Rule: Always use signed integers for your loop variables.

Iteration

Each time a loop executes, it is called an iteration. Often, we want to do something every n iterations, such as print a newline. This can easily be done by using the modulus operator on our counter:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

#include <iostream>

// Iterate through every number between 1 and 50

intmain()

{

intcount=1;

while(count<=50)

{

// print the number (pad numbers under 10 with a leading 0 for formatting purposes)

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!

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

#include <iostream>

// Loop between 1 and 5

intmain()

{

intouter=1;

while(outer<=5)

{

// loop between 1 and inner

intinner=1;

while(inner<=outer)

std::cout<<inner++<<" ";

// print a newline at the end of each row

std::cout<<"\n";

++outer;

}

return0;

}

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 variable inner declared inside the while block instead of immediately following the declaration of outer?

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

Variable inner is declared inside the while block so that it is recreated (and reinitialized to 1) each time the outer loop executes. If variable inner were declared before the outer while loop, its value would never be reset to 1, or we'd have to do it with an assignment statement. Furthermore, because variable inner 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!

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.

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.

(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.

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.

Hi, I was making a program to check if a number is a palindrome. While doing that, I thought, if I can reconstruct the reverse of a number using single digits, then I can easily reconstruct the number itself. Turns out, not so easy. I’ve dry run this code on paper several times. I keep getting wrong answers. For single digits, I get (10,20,30…) for (1,2,3…). For double digits, for example 15, I get [(1+5)10]+1=61. My mistake constantly slips through my eyes. Please help me out. Here’s the code:

This was mine. Instead of letters, I used starting from a to go to 122 for the end of the characters in the order of the integer char uses. I think this is more performance efficient since static casting and such should only be done is absolutely neccessary.