Accepting User Input

1-minute read
Table of Contents

Notice how we have only been hard-coding values into our program. Often times we will want to have the user input these values. In C, we can use the function scanf() to accept values from the user. There are other functions, some of which we will address later on.

The basic format for using scanf() is:


scanf(format_string,address_1,address_2,...);

Take for example asking the user for their age:

#include <stdio.h>

int main(){
    int age;
    printf("Please enter your age: ");
    scanf("%d",&age);
    printf("Wow so you are %d years old huh?!\nDas crazyyy!!",age);
    return 0;
}
asking-for-age.c
Copy

The ampersand, &

We use the ampersand (&) to specify that we want to use the address (memory location) of the variable that follows. In this case, the variable is age. Scanf() requires the address of the variable in order to change its value. This is unlike printf() which takes a copy of the variable (no ampersand is needed in order to get a copy).

Printing the memory address of a variable

It is good to know the placeholder/format specifier to print memory addresses in C:

#include <stdio.h>

int main(){
    char character;
    printf("Please enter a character: ");
    scanf("%c",&character);
    printf("The character you entered (%c) is now located at %p\n",character,&character);
    return 0;
}
display-memory-addresses.c
Copy

Support us via BuyMeACoffee