Home > Programming > [C Tutorial 5] Taking Input From User

[C Tutorial 5] Taking Input From User

/* how to take input data from the user - so we can later perform operations on it */

Just like printf is used to display output, scanf is its counterpart used to take input from the user. Assume that we need a number as input from the user(you're gonna need them in almost every program you make). We first need to define a variable that will hold the value of this number. A C variable is used to hold a value - it will store the value we take from the user.

So, there are essentially three steps we need to program this :

Step 1 - declare a variable to store value that the user will enter
Syntax - int a; declares a variable called a(you can call it anything) of the integer type.

Step 2 - ask the user to enter a value
Syntax - using printf

Step 3 - take the value and store it in the variable
Syntax - scanf("%d", &a);
%d stands for "take the value" and &a stands for "store it the variable called a".

The Program :

#include <stdio.h>
#include <conio.h>

int main()
{
int a; /* Step 1 */
printf("Enter any number\n"); /* Step 2 */
scanf("%d", &a); /* Step 3 */
getch();
return 0;
}

Now, just to check it the program does what it's supposed to do. Let's display the value of a as the output. We just need to add another printf function to the above code :

#include <stdio.h>
#include <conio.h>

int main()
{
int a; /* Step 1 */
printf("Enter any number\n"); /* Step 2 */
scanf("%d", &a); /* Step 3 */

printf("The value you entered was %d", a); /* displays the value of a */

getch();
return 0;
}

  1. No comments yet.
  1. No trackbacks yet.