if you need to get an amount from the user, you would put a printf() function like this before
scanf():
Click here to view code image
printf("What is the amount? "); /* Prompt */ /* A scanf() would
follow */
A printf() before a scanf() sends a prompt to the user. If you don’t prompt the user for the
value or values you want, the user has no way of knowing what values should be typed. Generally, the
printf() requests the data from the user, and the scanf() gets the data that the user types.
Let’s write a program with a few simple scanf() statements—after all, it is the best way to learn:
Click here to view code image
// Example program #1 from Chapter 8 of Absolute Beginner's Guide to
// C, 3rd Edition
// File Chapter8ex1.c
/* This is a sample program that asks users for some basic data and
prints it on screen in order to show what was entered */
#include <stdio.h>
main()
{
// Set up the variables that scanf will fill
char firstInitial;
char lastInitial;
int age;
int favorite_number;
printf("What letter does your first name begin with?\n");
scanf(" %c", &firstInitial);
printf("What letter does your last name begin with?\n");
scanf(" %c", &lastInitial);
printf("How old are you?\n");
scanf(" %d", &age);
printf("What is your favorite number (integer only)?\n");
scanf(" %d", &favorite_number);
printf("\nYour intitials are %c.%c. and you are %d years old",
firstInitial, lastInitial, age);
printf("\nYour favorite number is %d.\n\n", favorite_number);
return 0;
}
So those scanf() statements are not so bad, right? Each one is partnered with a printf()
statement to let the user know what to type. To see how confusing scanf() would be without a
preceding printf() statement, comment out any of the printf() statements before a scanf(),