Help with "while"

I am brand new to C++ and can't figure out for the life of me what is going on with this code. I am struggling as to the reasoning behind the console output always being a number in an increment of 5 regardless of the user input??? I have tried handwriting the code with the number I input and see no connection or formula for the total always being an increment of five. Please help!!!! :(

#include <iostream>
using namespace std;

int main()
{
int num = 1;
int number;
int total = 0;

while (num <= 5) {
cin >> number;
total += number;
num++;
}
cout << total << endl;

return 0;
}
There are two numbers of interest here:

- user input (and its sum)
- the loop counter

The loop executes five times: num ← 1, 2, 3, 4, 5.
int num = 1; 
while (num <= 5) { 
num++;

The five inputs, whatever they are, are summed into total. They will sum to whatever you want; not necessarily a multiple of five.

The main problem here is the bad variable names, which are all read by your human brain as "number", making it easy to confuse their relationship.

Here the program is rewritten a little:
- using better names
- putting related stuff together

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
  int user_input;  // no need to guess what this is
  int sum = 0;     // or this

  for (int n = 0; n < 5; n++)  // the input counter is all in one spot
  {
    cin >> user_input;
    sum += user_input;
  }

  cout << sum << "\n";
}

Hope this helps.
Duoas,

Thank you so much!!! It finally makes sense and you also taught me that the function for "for" is a loop counter. I didn't have the slightest clue and that would appear to be what was catching me up! Thank you again :D
Topic archived. No new replies allowed.