avg is used within the for loop as a running sum and only becomes the average when it is finally divided by 5 on line 19. You set avg = 0.0 so the sum starts at zero. The for loop is executed 5 times. Each time through the loop the following happens:
cout<<"Enter a value:";
The user is prompted to "Enter a value:"
After the user enters a number and hits the Enter
key, the number is stored in the variable val
The equal symbol is not the same as the equal symbol as used in a mathematical equation, but is called the assignment operator. Think of it as "Evaluate the expression on the right hand side of the equal sign and store (or assign) this value to the variable on the left hand side of the equal sign."
line 18: Marks the end of the for loop at which juncture the variable i
is incremented and the condition i<5 is checked and if true the loop is executed again. Finally when i=5 the condition will be false and execution will continue at the next statement following the for loop.
This divides the running sum avg by 5 and stores it back in avg.
Let's trace the for loop with some specific values entered by the user. I'll use the same names Cubbi used above for those values.
val1=3.0, val2=-4.0, val3=1.0, val4=7.0, val5= -2.0
val = val1 = 3.0
Evaluate avg+abs(val) which is 0.0 + 3.0 =3.0 and store this in avg so avg=3.0
val = val2 = -4.0
Evaluate avg+abs(val) which is 3.0 + 4.0 =7.0 and store this in avg so avg=7.0
val = val3 = 1.0
Evaluate avg+abs(val) which is 7.0 + 1.0 =8.0 and store this in avg so avg=8.0
val = val4 = 7.0
Evaluate avg+abs(val) which is 8.0 + 7.0 =15.0 and store this in avg so avg=15.0
val = val5 = -2.0
Evaluate avg+abs(val) which is 15.0 + 2.0 =17.0 and store this in avg so avg=17.0
i=5 and the loop ends.
line19: divide avg by 5 and store the result in avg so avg=17.0/5 = 3.4
A few additional comments about the code:
1. The practice of defining all variables at the beginning of a function has the mark of an old C programmer. C++ programmers generally prefer to define variables as close as possible to where they are first used.
Consider line 8
The variable i is not used except in the for loop so why not define it there? You can eliminate line 8 and change the first line of the for loop to:
2. Line 9
is certainly legal code, however most programmers generally give each variable declaration its own line. Variable names that are strung across the line horizontally are harder to read than if each is on its own line. In addition, it usually a good idea to initialize variables when they are declared. Line 11 which sets avg to zero can actually be moved up to the line where the variable is declared. I would change lines 9-11 to:
The final result:
using namespace std;
cout<<"Enter a value:";
cout<<"Average of absolute values:"<<avg;