Reputation: 27
I am a few weeks into programming in C++, and I am having a hard time understanding the Do-While Loop. Specifically, I do not understand this piece of code
#include<iostream>
using namespace std;
int main()
{
int sum = 0;
int y = 0;
do
{
for ( int x = 1; x < 5; x++)
sum = sum + x;
y = y+1;
} while ( y < 3);
cout << sum << endl;
return 0;
}
and its result:
30
I do not know how it resulted in 30, and it would be nice if I could get an explanation for this specific block of code. Thank you.
Upvotes: 0
Views: 183
Reputation: 7
Your program does 10+10+10, because you write it so it does the sum of integer numbers smaller than 5.
And you said do it while y<3 which means it will do it for values from 0 to 2 so it does 1+2+3+4==10 for values 0,1,2 which is 3 times and give you the result of 30.
Upvotes: 0
Reputation: 914
do ... while (cond)
loop works that way, that the condition cond
is checked after first iteration of the loop (so it goes at least through one iteration). When you enter that loop first, you encounter for
loop, which sums all integers in range from 1 to 4. The result of sum
after first iteration of outer loop is 10 and value of y
is now 1, so we move to the next iteration. Again we sum all numbers in inner loop and we add the result to the previous result of sum
(which was 10), now the result is 20. We increment y
, so it is 2, condition y < 3
still holds, so we move to the next iteration. Again we sum numbers, sum
is now 30 and we increment y
, so it is 3. Condition of do ... while
loop does not hold anymore, as y
is now 3, which is not smaller than 3. At this moment sum
is 30 and it gets printed on standard output.
Upvotes: 0
Reputation: 124
From that, what I see, the the code goes into the do block, it sees the for loop, executes that loop 4 times, you then proceed to increment y, and then the process is done 2 more times.
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int y = 0;
do {
// the code sees this for loop and executes it 4 times
for (int x = 1; x < 5; x++)
sum = sum + x;
y = y + 1; // you increment y by 1, then the code goes back up and repeats the process 2 more times
} while (y < 3); // execute this block 3 times in total
cout << sum << endl;
}
Upvotes: 1