C++: The while loop

The if statement check for validity of an expression and execute a block of code once.

We use a while statement to run a block of code if an expression is evaluated to true.

Say you are a rock fan and you are collecting rock albums and would like to stop when you have collected 10 albums.

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

void main()
{

	int album = 0;

	while (album < 10) {
		album++;
		cout << "I have " << album << " albums\n";
	}
	cout << "\n";
	cout << "I have collected 10 rock albums\n";
	cout << endl;

}

Let’s first look at the statement album++.

The ++ operators are put after the album and this is called post-increment.  Since album is an integer, it will add a value of 1 to it.

For example, in the above example, the album starts with 0 but after running album++ in line 11, the first line printed is:

I have 1 albums.

It is worthwhile to figure out why the last album printed out is 10 when the while expression is (album < 10) in line 10.

whilestatement

 

Series Navigation<< C++: The if-else statement
C++: Combining while loop and if statement >>