scanf is the dual function of the
printf function for keyboard input.
scanf is a function of the
// 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.
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);
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
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
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².
Which syntax is correct?
&before the variable. Try again...
scanf, why is the
& mandatory before the variable?
Which instruction will ask for the variable
long double speed;