While Loops

The for loop does 3 things for you: initialize, test, and increment the variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Read in 3 numbers: find total, using a for loop
#include <iostream>
using namespace std;
void main(){ 
  int num, total=0;
  int i; //we will use i to run the loop
  for(i=0;i<3;i++) {
    cout<<"Enter a number:";
    cin>>num;
    total=total+num;
  }
  cout<<"Total="<<total<<"\n";
  system("pause");
} //main
CODE
output

A while loop only does the test. We must include the statements to initialize (line #6) and increment (line #11):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Read in 3 numbers: find total, using a while loop
#include <iostream>
using namespace std;
void main(){
	int num, total = 0;
	int i=0; //we will use i to run the loop
	while(i<3) {
		cout << "Enter a number:";
		cin >> num;
		total = total + num;
		i++;
	}
	cout << "Total=" << total << "\n";
	system("pause");
} //main
CODE
output

If you work through the code carefully, you will notice that the value of i is 0, 1, and 2 inside the loop. When i becomes 3, the loop ends. When the loop ends, the next
statement after the loop is executed.

Another very important point to note is that the body of the loop is either the single
statement that follows the for clause, or all of the statements enclosed in curly braces{ }.

If you leave off the curly braces the prompt will print 3 times, and then you will
have an opportunity to input just one number. Try it!

NEXT: A loop to count