Hi, thanks in advance for your help.
I am working on my pseudocode as much as the syntax of the language.
This is a very simple program but when I run it. It gives me the correct sum but either 0 or a negative integer. Why is that ?
I have created 3 integers named a , b and sum. Sum is the addition of a and b. I have used gin for user input which when user input number, the number is displayed when asked for it. Then sum is outputted.
#include <iostream>
usingnamespace std;
int main()
{
int a;
int b;
int sum = a + b;
cout << "Enter first integer:";
cin >> a;
cout << "Enter second integer:";
cin >> b;
cout << "sum is:" << sum<<endl;
return 0;
}
Put the code you need help with here.
***can you TELL ME where my logic fails me?
don't give solution but rather if you can explain. I would appreciate it.
This is what I get when i run program
------------------------------------
Enter first integer:7
Enter second integer:7
sum is:0
Program ended with exit code: 0
ok, so that worked, why? I was under the impression that if I just cout <sum> it would know that it was a+b since I told it to add those two integers previously?
ok, so the line of code that you corrected was wrong. I copied and pasted it incorrectly. So here it was it was before.
{
cout << "sum is:" << sum<<endl;
return 0;
}
You have to be aware that the program executes from top to bottom.
So at the moment you originally initialize sum to be (a+b) both a and b are still zero.
That initializes sum with a value of 0+0 = 0, which it keeps until the moment you cout this value.
You should assign the values of a and b before you calculate the value of sum.
This is not an equation. This is an assignment. You're not establishing a relationship between these numbers, like you think you're doing. You're assigning the sum of 'a' and 'b', whatever values they may have at that moment, to 'sum'. Since 'a' and 'b' contain garbage (since they haven't been initialized at that instant), 'sum' also contains garbage.
#include <iostream>
usingnamespace std;
int main()
{
int a;
int b;
cout << "Enter first integer:";
cin >> a;
cout << "Enter second integer:";
cin >> b;
int sum = a + b; // initialize sum to (a + b)
cout << "sum is:" << sum<<endl;
return 0;
}
The original code would be undefined behavior because at the time of initializing sum a and b have random data that is in the memory locations created by their declarations.