Lesson 4.2. scanf

scanf is the dual function of the printf function for keyboard input.

scanf

scanf is a function of the stdio.h library.

// Enter an integer from the keyboard and store it in the variable x
scanf ("%d", &x);

It is possible to enter several variables at the same time, but I do not recommend this syntax which can be problematic if not mastered. Here is an example:

scanf ("%d%d", &x, &y);

Note that the second parameter is preceded by a &. This character indicates that it is a pointer. We will come back to this later in the course on pointers, but without this character, the function would not be able to write to the variable.

Be sure not to forget the & before the variables in the scanf function parameters.

Example

The example below asks the user to enter a distance in kilometers and converts it to miles:

float distance_km, distance_miles;

// Entering the distance on the keyboard
printf ("Enter the length (km) : ");
scanf ("%f", &distance_km );

// Convert the distance to miles
distance_miles =  distance_km / 1.609;

// Displays the result of the conversion
printf ("%.1f km = %.1f miles\n", distance_km, distance_miles);

Exercise 1

Write a program that asks the user to enter an angle in degrees. The program displays the angle converted to radians as shown in the example below:

Enter the angle in degrees: 45
45.00 degrees = 0.7854 radians

Exercise 2

Write a program that asks the user to enter the length and width of a rectangle. The length and width are of type integer. The program displays the perimeter of the rectangle according to the example below:

Enter the width of the rectangle: 5
Enter the length of the rectangle: 3
The perimeter of the rectangle is 16

Exercise 3

Write a program that asks the user to enter his weight in kilograms and height in meters. The program then calculates the user's BMI according to the example example below. The formula to calculate BMI is shown here.

What is your weight in kilograms?
63
What is your height in meters?
1.7
Your BMI is 21.8 kg/m².

Quiz

Which syntax is correct?

Check Bravo! Do not forget the & before the variable. Try again...

In an scanf, why is the & mandatory before the variable?

Check Bravo! The scanf function expects a pointer without which it could not write to the variable. Try again...

Which instruction will ask for the variable speed?

long double speed;
Check Bravo! You must put the format code associated with the type of the variable. Try again...

See also


Last update : 11/21/2022