While Statement

Can someone please explain further for me on this part of the code

sum += val; //I understand that it is the same as sum=val+sum and I am able to use it later in cout to represent the total sum



++val; //I dont understand this;adds one to val,and keep repeating until it reaches 10,but isn't val stored to sum and then val is increased?and how did they add up all inclusive ?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include <iostream>

using namespace std;

int main()
{

    int sum = 0, val = 1;
    // keep executing the while as long as val is less than or equal to 10

    while (val <= 10) {

        sum += val;

        ++val;

    }

    cout << "Sum of 1 to 10 inclusive is " << sum << endl;
    return 0;
}



Thanks
Last edited on
This line:

sum += val;

does NOT alter the value of 'val' at all.
Ok I will give you.a full explain toon on that loop

Firstly sum += val is actually sum = sum + val

In the programme you want to add every number from 1 to 10

So sum += val will start at 1 with the loop

Adds 1 to sum

Then goes to two because of ++val and dose that until 10

Do you get it now

And I noticed you got that code from C++ primer try making you own programmes with while loops
Thanks but where or how does it tell the code to add the 1,2...10 ?

I know every loop it increases by one but I dont see the adding of each number?thanks in advance,yes I just got the book
Stick a breakpoint on line 15, then add watches for the 2 variables. you should see how they change on each entry and exit in that loop.

OR

on line 16 add a std::cout to print out both values to the screen, so you can see how they change.
Topic archived. No new replies allowed.