Home > Back-end >  What does happen to the variable value ''sum'' inside the FOR loop?
What does happen to the variable value ''sum'' inside the FOR loop?

Time:06-22

In this code the output is "0 1 18", but I can't understand why it's not "64 1 18". What does happen here?



#include <iostream>
using namespace std;

int main ()
    {
        int sum = 0, i = 1, sum2=4;
            for(int sum = 10, i = 2; i <= 10;   i)
            {
                //sum  = i;
                sum = sum   i;
                cout << "i= " << i << " sum= " << sum << endl;
                sum2 = 18;

            }

        cout << sum << " " << i << " " << sum2;

        return 0;
    }

CodePudding user response:

So,here sum carries two different values, and the operation is carried on the sum initialized inside the for loop. For your desired output you need to initialize sum at the beginning.

CodePudding user response:

because you use sum and i as parameter in for loop and loop parameter will destroyed after loop end. you should edit your code

 #include <iostream>
 using namespace std;
    
        int main()
        {
            int sum = 10, i = 1, sum2 = 4;
            for (int k = 2; k <= 10;   k)
            {
                
                sum = sum   k;
                cout << "i= " << k << " sum= " << sum << endl;
                sum2 = 18;
        
            }
        
            cout << sum << " " << i << " " << sum2;
        
            return 0;
        }
  • Related