Skip to main content
Logo image

Section 4.8 User Input Using scanf()

It is possible to have the user (the person sitting in front of the computer screen) modify the value of a variable while the program is running! To do so the user needs to enter a value (this is typically done by typing on the keyboard) and your program needs to be ready to accept such an input value and store it in a variable. The C-command to accomplish this is scanf().
The following code asks the user for their age, has them enter it and then prints it out. You’ll notice the strange ampersand (&) character in front of the variable in which we are storing the user input. We’ll explain this a bit later - for now: don’t worry.

admin.....open in new window

Try it out by hitting the “Run” button! When prompted, enter your age.
You can read multiple entries with one scanf() statement if you wish (or you can simply use multiple scanf() statements in a row):

admin.....open in new window

Let’s get back to our multiplication table. Rather than printing the x7 table, in this next example, we’ll have the user enter which multiplication table to print:

admin.....open in new window

Activity 4.7. Adding User Input.

Please write a program that adds integers, entered by the user.
First, ask the user to enter the number of integers they wish to add. Next, use a for-loop that runs the desired number of times, and in which you continually ask the user to enter another number that then gets added to the sum.
When the loop terminates, print the result to the screen.
Here is a sample session, with simulated user input in bold:
How many numbers do you wish to add? 5
Please enter number 1: 7
Please enter number 2: 13
Please enter number 3: 4
Please enter number 4: -3
Please enter number 5: 9

admin.....open in new window

When you are done, please copy the code you added into the box below: