Write your question here.
Hi, I am self teaching myself C++ (I have some prior experience) and going through the basics. When typing in a basic calculator, I have a question regarding these two statements:
(Statement 1)
#include <iostream>
usingnamespace std;
int main()
{
int a;
int b;
int sum;
cout << "Enter a number for a \n";
cin >> a;
cout << "Enter another number for b \n";
cin >> b;
sum=a+b;
cout << "The sum of a and b is: " << sum;
return 0;
}
[/code] (Statement 2)
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int sum;
sum=a+b;
cout << "Enter a number for a \n";
cin >> a;
cout << "Enter another number for b \n";
cin >> b;
cout << "The sum of a and b is: " << sum;
return 0;
}
[/code]
For Statement 1, when I enter 4 for both a and b, it calculates it correctly as 8.
But for Statement 2, when I enter 4 for both a and b, it calculates it as 6040903 (or something like that). Why is that Statement 1 is able to give the right solution?
#include <iostream>
usingnamespace std; // eventually learn to avoid this, Google why it is bad :+)
int main()
{
int a = 0;
int b = 0 ;
int sum = -9999; // hopefully this won't clash with an actual correct answer
cout << "Enter a number for a \n";
cin >> a;
cout << "Enter another number for b \n";
cin >> b;
//sum=a+b; // <--- intentional mistake here, commented out the whole line
cout << "The sum of a and b is: " << sum; // still gives a identifiable but wrong answer
return 0;
}