Please explain the process | Sololearn: Learn to code for FREE!

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; }

c++

6/26/2017 4:09:48 PM

Sanjeev Kumar

4 Answers

New Answer

+4

b = b * i; will achieve what you are trying to do.

+1

thanks @chaoticdawg and @hatsyrei

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.

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 ??