-3

My code:-

#include<stdio.h>
#include<conio.h>
void main(){
    int a,b,c;
    printf("Enter the 1st number:");
    scanf("%d",a);
    printf("Enter the 2nd number:");
    scanf("%d",b);
    c=a*b;
    printf("The value of %d * %d is %d",a,b,c);
    getch();
}

Now when I execute this program in Turbo C++, This gives as the output:-

Enter the 1st number:10
Enter the 2nd number:10
The value of 1308 * 1320 is 22625

Why is this happening?

VatsalSura
  • 926
  • 1
  • 11
  • 27
Arko991
  • 47
  • 1
  • 6
  • You haven't passed scanf pointers. Add an ampersand in front of "a" and "b" on the scanf lines. Your title suggests you already knew this was the problem. – Borealid Jul 16 '16 at 08:01
  • @EJP, `scanf("%d",a);` should rather be `scanf("%d",&a);` and so on for all the `scanf()` statements. – abhishek_naik Jul 16 '16 at 08:03
  • Yes @Borealid I knew ampersand was the problem in the first place but I wanted to know what ampersand does and without ampersand how does the values taken by the system becomes 1308 and 1320 for 'a' and 'b' respectively? Sorry about not mentioning this in the question itself. Maybe I should've checked the writing of my question before posting this. – Arko991 Jul 16 '16 at 15:21

1 Answers1

0

You were missing an & ampersand when taking values from user. You have to take the values in the address of the variable and not the variable itself, so use & while taking values from user in scanf function.

#include<stdio.h>
#include<conio.h>
void main(){
    int a,b,c;
    printf("Enter the 1st number:");
    scanf("%d",&a);
    printf("Enter the 2nd number:");
    scanf("%d",&b);
    c=a*b;
    printf("The value of %d * %d is %d",a,b,c);
    getch();
}
VatsalSura
  • 926
  • 1
  • 11
  • 27
  • Thank you! That was helpful :) .But can you tell me one more thing, how does the value becomes 1308 and 1320 for 'a' and 'b' respectively when I did not place ampersand? How does that work out? – Arko991 Jul 16 '16 at 15:29
  • @Arko991 They are garbage values in your memory. You didn't assign any values to them and did arithmetic operations on them, so it is taking garbage values from your memory on that location. – VatsalSura Jul 16 '16 at 15:32
  • Okay I got it but one more thing, is those garbage values random? meaning will the values(1308 and 1320) be the same if I again execute my program without ampersand or will it give another values for 'a' and 'b'? – Arko991 Jul 16 '16 at 16:17
  • @Arko991 The garbage values will always be random, depending upon the address your IDE is providing to your variables. – VatsalSura Jul 16 '16 at 16:33
  • Thanks. I understand it now. :) – Arko991 Jul 17 '16 at 01:00