why this not giving me the right total?

#include <iostream>
using namespace std;

int main()
{ // start brace

int sum;
int num;
//------------
{
cout <<"\nPlease enter a number:" << endl;
for (int i=0,sum=0;i<=2;i++)
cin >> num;
sum=sum+num;
}

{
cout << sum;
}

return 0;
}
//-------------------------------------------------
//why sum=sum+num is not giving me the right total
//I would love to have an answer if it is one please.
//yes, I asked about this early, but it not been solved yet.

//Thanks,
//Chester
Hi samtheman,

You may wish to define your variable sum and not just declare it : that is, give it an initial value.
That's a good way to do with variable ^_^

Here :
 
int sum = 0;

You cannot define sum in the for loop like that because you define a local int i just before, your sum will also be declare locally as a local variable of the for loop.
When the for loop ends, your local variable sum will be cleaned and your "global" sum variable will still be unchanged.

You can also write "sum += num;"... it doesn't change a lot nowadays but semantically speaking, it's a lot better ;o)

Also, your for loop doesn't encapsulate the "sum" instructiion, so only when your loop is finished, only then you sum the last value of "num".

This is the correct version :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
	int const nbofNumberToBeAdded = 3;
	int sum = 0;
	for(auto i = nbofNumberToBeAdded; i--;)
	{
		int num;
		std::cout << "\nPlease enter a number: ";
		std::cin >> num;
		std::cout << "> sum = " << sum << " [" << num << "]" << std::endl;
		sum += num;
	}
	std::cout << sum << std::endl;
	//--
	return 0;
}


As a commentary, if not needed, just use the "habitual" form of the for loop :
for(auto i = 0; i < n; ++i)...
With the "<" comparison to a max value (n) where n means "n times". It's more readable.
Also in that case, the better form is
for(auto i = n; i--;) ...

I think that you've put the maximum error possible in your example \o/... you know what they say ?
Fail fast, fail often ^_^


So I'm sure that you are on the good way to be excellent in C++ (thumbs up)
Last edited on
Topic archived. No new replies allowed.