Sure, let's discuss taking user input in C using simple language:
User input refers to data provided by the user during the execution of a program. It allows users to interact with the program, providing information that can be used by the program to perform certain tasks.
In C, you can use the scanf()
function from the stdio.h
library to take input from the user. This function reads input from the standard input stream (usually the keyboard) and stores it in variables.
Let's create a simple program that asks the user for their name and age, and then prints out a greeting with that information.
#include <stdio.h>
int main() {
char name[20]; // To store the user's name
int age; // To store the user's age
// Ask the user for their name
printf("What's your name? ");
scanf("%s", name); // Read the user's input and store it in the 'name' variable
// Ask the user for their age
printf("How old are you? ");
scanf("%d", &age); // Read the user's input and store it in the 'age' variable
// Greet the user
printf("Hello, %s! You are %d years old.\n", name, age);
return 0;
}
In this example
name
to store the user's name and age
to store the user's age.printf()
to ask the user for their name and age.scanf()
to read the user's input. Notice %s
is used to read a string (name) and %d
is used to read an integer (age). Also, for reading an integer, we need to use &
before the variable name to get its memory address.printf()
again to greet the user with the provided information.When you run this program, it will prompt you to enter your name and age, and then it will greet you with the entered information.