I dont get this line. need help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
    int grade;
    double average;
    double sum=0;
    char lettergrade;
    int r;
    int g;


    for(r=0; r<5; r++){
    cout<<" Grade"<<r+1<<" ";
    cin>>grade;
    sum= sum+grade; I DON'T GET THIS LINE




    }
average= sum/5;
    cout<<" Your avg "<< average;



    }



 


I don't get why its sum+grade? sum has no value so how is it sum+grade and how exactly does this line add up all the grades? please explain
Last edited on
Hey there. Because this is in a for loop, sum will be 0 zero until sum+grade occurs. After that, sum will have an actual value next time the loop occurs, and so on and so forth. After all the grades have been added into the sum, the average is then calculated and displayed. Hope this helped :)
Last edited on
What that line basically does is add the value of grade to the current value of sum, then assign the result to sum. BTW, you don't need to declare the variables used in a for loop outside the for. You could delete line 12 and rewrite line 16 as:

for (int r = 0; r < 5; ++r)

and it will work exactly the same. In fact, this is somewhat preferred, that way you don't aren't populating main with extra variables that aren't needed elsewhere in it.
Last edited on
Topic archived. No new replies allowed.