In this lab, you will learn how to get input from the user using the scanf
function in C. You will write a program that prompts the user for their name and age, captures the input, and then displays a message using the provided information. This is an important step in understanding how programs interact with users in real-world applications.
By the end of this lab, you will be able to:
scanf
function to read user input in C.gcc
.cd c_programs
Use the Nano editor to create a new C program file:
nano user_input.c
In the Nano editor, type the following code to prompt the user for their name and age:
#include <stdio.h>
int main() {
char name[50];
int age;
// Ask the user for their name
printf("Enter your name: ");
// Get the user's name (string input)
scanf("%s", name);
// Ask the user for their age
printf("Enter your age: ");
// Get the user's age (integer input)
scanf("%d", &age);
// Display the user's input
printf("Hello, %s! You are %d years old.\n", name, age);
return 0;
}
Save the file by pressing CTRL + O
, then press Enter
. Exit the Nano editor by pressing CTRL + X
.
To compile your C program, use the gcc
compiler. Run the following command:
gcc user_input.c -o user_input
If there are no errors, the command will create an executable file named user_input
. You can list the files to confirm:
ls
You should see user_input
in the list.
Now that the program is compiled, run it by typing:
./user_input
The program will prompt you for your name and age. For example:
Enter your name: John
Enter your age: 25
After entering the name and age, the program will display a message like this:
Hello, John! You are 25 years old.
Enter your name: Alice
Enter your age: 30
The program should display:Hello, Alice! You are 30 years old.
char name[50];
: This line declares a string (an array of characters) to store the user’s name. The maximum length of the name is set to 50 characters.int age;
: This declares an integer variable to store the user’s age.scanf("%s", name);
: This function reads the user’s name from the input.scanf("%d", &age);
: This reads the user’s age. Note the &
symbol before the variable age
— it is required to provide the memory address of the variable to scanf
.printf("Hello, %s! You are %d years old.\n", name, age);
: This prints the greeting message, using %s
to display the string (name) and %d
to display the integer (age).In this lab, you learned how to use the scanf
function to get input from the user in C. You built a program that asks the user for their name and age and then prints a message based on their input. This is a crucial concept, as user interaction forms the foundation of many C programs. By using scanf
, you can handle different types of input and create interactive programs that respond to user-provided data.