In this post, we will learn how to get input from the user in C Programming language.
This program takes input from the user using scanf() function and displays it on the screen using printf() function.
We will learn to take input of the following data types:
- Int data type
- Character data type
- String data type
So, without further ado, let’s begin this tutorial.
C Program to Get Input From User(Integer)
// C Program to Get Input From the User #include <stdio.h> int main(){ int num; // Asking for input printf("Enter a number: "); scanf("%d", &num); // Display output printf("You entered: %d", num); return 0; }
Output
Enter a number: 20
You entered: 20
How Does This Program Work ?
int num;
In this program, we have declared an int data type variable named num.
// Asking for input printf("Enter a number: "); scanf("%d", &num);
Then, the user is asked to enter a number. The input is taken with the help of scanf() function. The scanf() function reads characters from the standard input(keyboard).
// Display output printf("You entered: %d", num);
Then, we have used printf() function to display the entered number on the screen.
Here, we have used %d format specifier because %d tells printf that the corresponding argument to be treated as an integer value.
C Program to Get Character From the User
// C Program to Get Character Input From the User #include <stdio.h> int main(){ char ch; // Asking for input printf("Enter a character: "); scanf("%c", &ch); // Display output printf("You have entered: %c", ch); return 0; }
Output
Enter a character: J
You have entered: J
C Program to Get String Input From the User
// C Program to Get String Input From the User #include <stdio.h> int main(){ char str[25]; // Asking for input printf("Enter a string: "); scanf("%s", &str); // Display output printf("You have entered: %s", str); return 0; }
Output
Enter a string: CodingBroz
You have entered: CodingBroz
Conclusion
I hope after going through this post, you understand how to get input from the user in C Programming language.
If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to assist you.
Also Read: