c ++

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#include <iostream>
using namespace 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
Last edited on
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;
}
Last edited on
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.
int sum = a + b;

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace 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.
@WheatFieldOnFire essentially yes. My response was to the OP.
Thanks to everyone for your help.
Topic archived. No new replies allowed.