-
Help.
I have drafted this code below, for some reason int C is returned as the address instead of sum of two ints. If anybody can help, I would be very grateful..
Code:
#include <stdio.h>
int main()
{
int A, B;
int C = A + B;
printf("Enter A please\n");
scanf("%i", &A);
printf("Enter B please\n");
scanf("%i", &B);
printf("%i + %i = %i\n", A, B, C);
if(C < 90)
{
printf("It's less than 90\n");
}
else if(C > 90)
{
printf("It's greater than 90\n");
}
return 0;
}
-
You should perform the addition and assign the result to C after you have read in the values of A and B.
-
-
Thanks laserlight, but if you can , please explain what you mean.
-
Code:
int A, B; // <--- 'A' and 'B' are uninitialized here, and thus contain garbage
int C = A + B; // <--- 'C' is the sum of two garbage values, hence contains a garbage value itself
printf("Enter A please\n");
scanf("%i", &A); // <--- Here 'A' gets a value
printf("Enter B please\n");
scanf("%i", &B); // <--- Here 'B' gets a value
printf("%i + %i = %i\n", A, B, C); // <--- ...but 'C' is still a garbage value. The addition should go after 'A' and 'B' are received.
-
What laserlight said is actually this
You want the program to add A and B into C.However at line 7 the only thing your program knows(let's say the world of the program) is this
Code:
#include <stdio.h>
int main()
{
int A, B;
int C = A + B;
In other words your program knows only that there are three integers,and C is equal to A and B..But values of A and B are unknown at that time...Let me make a paromiosis for you.It is like you ask me to add two numbers and have me do this before you tell what these numbers are!I know that they are numbers,but what numbers?1,3,5,3738273927?What number?You inform me about what numbers should i add only after i have already made the addition...So what numbers did i actually added?
You do not know!This is what we call unexpected behaviour in computer science(in some cases the values are set by default,but it is good for everybody that you clearly state what the value of every variable is!)
In your code,you perform the addition before getting the input.That's wrong.You should move a line(or move the addition i would say) after you have received the input :)
-
Thanks
Ok , I've got it.
Thank you again....
It just makes so much sense to add A & B after program knows A & B...
(How about that...?)
Thanks again...