4️⃣

2.4 Input

 

Input

scanf()

In addition to printing an output to the screen, as programmers, we want to be able to take input from the user as well. In order to do this, we can use the scanf() function. Let’s explain this with an example:
 
int number; printf(“Enter a value: “); scanf(“%d”, &number); printf(“The value of number is %d”, number);
 
In the first line of code above, we created a variable called “number”, but we did not give it a value yet. Then, in the second line of code, we printed a message to prompt the user to enter a value. In the third line of code, we used the scanf() function to take the value the user gave us and assign it to the variable “number”. We used the placeholder %d to signal to the computer that the user will be entering a value of type int and after the comma, we gave the name of the variable that the user’s value will be stored in.
 
Notice that right before the variable name in the scanf() function, we used the “&” symbol. This symbol is called an ampersand, and it tells the computer that the user’s input should be placed at the “address of” the following variable name. In the fourth line of code, we printed out the new value of the variable “number”. Here is what would be displayed to the user if they run the above code (the text in purple is what the user could have typed):
 
Enter a value: 8 The value of number is 8
 

getch()

We know that scanf() gets input from the user, but what if we want to keep it short and sweet? getch() is a built-in function in C that allows the computer to receive one character long input from the user.
printf("Enter a value: %c", getch());

Practice

Number

Create a program that prints out whatever number the user types into the console.
Solution Code
#include <stdio.h> int main(void) { printf("Enter a value: %c", getch()); }
 

Previous Section

Next Chapter

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.