Reputation:
I am practicing c programming from the very beginning, but when I execute simple C program to add two numbers, I got unexpected output, I am not able to figure it out, can anyone provide the detailed explanation of how the compiler works behind the scene for this output.
Here is the mentioned code. I am using basic turbo IDE
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c=0;
clrscr();
printf("Enter two numbers:");
scanf("%d%d", &a,&b);
c=a+b;
printf("sum of two numbers are %d", &c);
getch();
}
Output:
Enter two numbers:1
2
sum of two numbers are -16
Upvotes: 0
Views: 298
Reputation: 1
You are typing the wrong syntax of printf
use this:
printf("sum of two numbers are %d",c);
Upvotes: 0
Reputation: 3355
You have mistake in line :-
printf("sum of two numbers are %d", &c);`
Change it to :-
printf("sum of two numbers are %d", c);
&c
is used when you want to print address.
Modified code :-
#include <stdio.h>
#include <conio.h>
void main()
{
int a, b, c = 0;
clrscr();
printf("Enter two numbers:");
scanf("%d%d", &a, &b);
c = a + b;
printf("sum of two numbers are %d", c); // not &c
getch();
}
Output :-
Enter two numbers:3
5
sum of two numbers are 8
Turbo c is very outdated.Try gcc
(IDEs like CodeBlocks) . Also make sure that your code is intended properly.
Upvotes: 1
Reputation: 586
The problem seems to be that you used the address-of operator on the variable c
where you did not need to. &c
is a pointer to c
, so when you print it out you are actually trying to print the memory address of c
rather than the integer value stored there, leading to unexpected output. So
printf("sum of two numbers are %d", &c);
should become
printf("sum of two numbers are %d", c);
Upvotes: 1