For Loops

Consider the program below. This program reads in a number and adds to the total 3 times. There is just one variable for the input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Read in 3 numbers: find total, version 2
#include <iostream>
using namespace std;
int main(){ 
  int num, total=0;
  cout<<"Enter a number:";
  cin>>num;
  total=total+num;
  cout<<"Enter a number:";
  cin>>num;
  total=total+num;
  cout<<"Enter a number:";
  cin>>num;
  total=total+num;
  cout<<"Total="<<total<<"\n";
  system("pause");
  return 0;
} //main
CODE
Enter a number:34
Enter a number:10
Enter a number:-5
Total=39
Press any key to continue . . .

Note that the 3 lines 6, 7, and 8 are identical to lines 9, 10, and 11 and to 12, 13, and 14.

If we can rewrite a program to repeat the same lines several times, we can use a loop instead.

NEXT: A for loop to read 3 numbers