I've been trying the cs50 credit problem and i am stuck in the part where you add every other digit in the number. This is what i came up with.
#include <iostream>
using namespace std;
int main() {
int num = 123456789;
int sum, last, second;
while (num>0)
{
last = num/10;
second = last%10;
num /=10;
cout<<second<<endl;
sum += second;
num /=10;
}
cout<<"sum: "<<sum<<endl;
return 0;
}
Output:
8
6
4
2
0
sum: 20
It works and gives the sum of every other digit which is 20 in this case. But it gives a very different answer when i add more values and change it to long.
This is where it gives a different result.
#include <iostream>
using namespace std;
int main() {
long num = 123456789;
long sum, last, second;
while (num>0)
{
last = num/10;
second = last%10;
num /=10;
cout<<second<<endl;
sum += second;
num /=10;
}
cout<<"sum: "<<sum<<endl;
return 0;
}
Output:
8
6
4
2
0
sum: 140736744828580
The answer should be 20 but it gives a really big number. I think the problem is my computation in the while loop but I can't seem to find a solution which is why I posted it here. Thanks in advance.
In this line (1st version):
int sum, last, second;
as well as in this line (2nd version):
long sum, last, second;
sum
is uninitialized.
It is also not initialized further on, and then when this line is executed:
sum += second;
You cause Undefined Behavior (UB).
When UB happens, the C++ standard explicitly makes no guarantees about how the program will behave, so there's no point in reasoning about it.
The fact that with the int
version you got correct result is a matter of pure chance.
In order to fix it you simply have to initialize sum
(in my opinion it is best to define it in a separate line and initialize):
int/long sum = 0;