While Loops

Compare the two programs below.

1
2
3
4
5
6
7
8
9
10
11
12
13
// Print 0 1 2 3 4 5 
#include <iostream>
using namespace std;
int main() {
  int num=0;
  while (num<=5) {
     cout<<num<<" ";
     num = num+1;
  } // while 
  cout<<"\n";
  system("pause");
  return 0;
} // main
CODE
1
2
3
4
5
6
7
8
9
10
// Print 0 1 2 3 4 5 using while and ++
#include <iostream>
using namespace std;
int main() {
  int num=0;
  while (num<=5)
    cout<<num++ <<" ";
  cout<<"\n";
  return 0;
} // main
CODE

In the first program the body of the loop has 2 statements, one to print and one to increment num.

The second program has just one statement in the body of the loop: the increment is combined with the cout statement.

Notice that we don't even have to enclose the body of the loop in { } because there is just one statement.

Both programs print 0 1 2 3 4 5.

NEXT: Blast off 2 ways