Initializing variable

Hello, sorry for this silly question. I'm really new to C++. I really want to know why can't i get the summation from 50 to 100 when i initialize the "sum" variable inside the for loop? Why do i need to put it in the main function and before the for loop?



#include <iostream>

using namespace std;

int main()
{
int sum = 0;
for(int i=50; i <=100; ++i){
sum = sum + i;
cout << "the sum is " << sum << endl;
}
return 0;
}

Your question is not clear. Maybe you wanted to move the output statement to after the loop instead?
Last edited on
I mean, if i initialize the sum variable inside the for loop, it will just output the numbers from 50 to 100 but not the sum.

int main()
{
int sum = 0;
for(int i=50; i <=100; ++i){
sum = sum + i;
cout << "the sum is " << sum << endl;
}
return 0;
}

i want to know why i need to put the variable sum outside the for loop. is it because if it's inside the for loop, the main function can't use it?
Last edited on
It makes no sense to initialize sum within the loop. Each time it will be set to 0 and hence the addition from the last iteration will be lost.
ok, i think i got it. thanks for ur reply! :)
Topic archived. No new replies allowed.