0

Please explain the process

#include <iostream> using namespace std; int main() { int a,b,ans; ans=0; a=2; b=a*2; for(int i=1;i<=3;i++) { b*i; ans=ans+b; } cout <<ans; return 0; }

26th Jun 2017, 4:09 PM
Sanjeev Kumar
Sanjeev Kumar - avatar
4 odpowiedzi
+ 4
b = b * i; will achieve what you are trying to do.
26th Jun 2017, 5:03 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
thanks @chaoticdawg and @hatsyrei
26th Jun 2017, 5:27 PM
Sanjeev Kumar
Sanjeev Kumar - avatar
0
Before the loop: ans is set to 0 a is set to 2 b is set to a * 2, so b is 4 The for loop loops 3 times. in the body of the loop: b*i; just multiplies b * i, but it doesn't save the result back into any variable, so it has no effect. b will remain 4 throughout the program. 1st loop ans = ans + b (0+4) = 4 2nd loop ans = ans + b (4+4) = 8 3rd loop ans = ans + b (8+4) = 12 ans is 12 when the loop finishes and is output to the console.
26th Jun 2017, 4:39 PM
ChaoticDawg
ChaoticDawg - avatar
0
That means if I needed to increment the value of b inside the for loop, I would need another variable to store the incremental value of b ??
26th Jun 2017, 4:41 PM
Sanjeev Kumar
Sanjeev Kumar - avatar