C Programming, print and scan function

+1 Robert Summers · November 15, 2014
Hello, I am stuck. I cannot figure out why this program is not working. Please help.


#include <stdio.h>
#include <stdlib.h>

int main(){
    int fnum;
    int snum;
    int answer;

    printf("Enter First Number: ");
    scanf("%d", &fnum);

    printf("Enter Second Number: ");
    scanf("%d", &snum);

    printf("Your total is %d\n", &answer);

    return 0;
}

I keep getting a number higher than my actual answer.
I enter fnum as 3, snum as 2 and answer = 8237462.
Why is this? Thanks for the help in return.

Kind regards
Robert




Post a Reply

Replies

Oldest  Newest  Rating
+2 c student · December 5, 2014
you are printing the incorrect thing.

understand that the ampersand '&' symbol when attached to a variable represents the address of the variable in memory.
therefore &answer is the address of the variable "answer"

what you are looking to do i believe is to just print "answer" instead of "&answer"
0 Robert Summers · November 15, 2014
Same thing happens

#include <stdio.h>
#include <stdlib.h>

int main(){
    int fnum;
    int snum;
    int answer;

    printf("Enter First Number: ");
    scanf("%d", &fnum);

    printf("Enter Second Number: ");
    scanf("%d", &snum);

    answer = fnum + snum;

    printf("Your total is %d\n", &answer);

    return 0;
}
0 Robyn Jaime · December 8, 2014
@ c student...true answer....the "&" sign is for when printing address of variable (pointers) not value of variable. Also initialize variables before summing them.
  • 1

C

107,322 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator