Ask information to the user
Now let’s make our program dynamic, let’s back to our calculator program, we were making a hard coded operation (always adding the same numbers), if we ask the user the numbers that he wants to add, our calculator will be more like a calculator, a lot more useful.
printf function prints something on the screen, the
scanf gets the information typed by the user and saves it into a variable. As equal to
printf, to use
scanf we need to import the standard input and output library
Let’s see how to ask and get an integer value:
When the program comes to
scanf instruction, it will make a pause and wait for you to introduce a value, when you hit enter, the
scanf will take that value and store it in
user_number variable, after that, you can use that variable just as we have seen in the previous lesson.
Imagine that you introduced the number
5, the output would be:
Plese insert an integer number: 5 You introduced the number -> 5
How it works?
scanf works similar to
printf, you need to specify the type of data you are going to store with the same codes that you use to print them, so to save an integer value in a variable you use
%d and so on.
Let’s look again the
scanf in action:
Something more to notice is the ampersand
& symbol, that is very important, with it you indicate to
scanf where to store the value introduced by the user, don’t forget it.
The ampersand has a more complex explanation, we are going to see it in details in further lessons, but by now always use it as it.