Free2Code
Tutorials » Browse » Programming
Tutorials - Introduction to C - Taking Input
This article written by
  OldSite

Member since
  October 11, 2006

We can use the scanf() function to take input from the person running the program and assign the value to a variable. Here’s how it looks:

scanf("%d", &Number);

As with printf() we must use the right sign, here we will be dealing with an integer so we use %d. The second parameter is the variable to which we want to assign the value.

#include <stdio.h>

int main()
{
    int Number1, Number2, Sum;
    printf("Enter a number:");
    scanf("%d", &Number1);
    printf("Enter another number:");
    scanf("%d", &Number2);
    Sum = Number1 + Number2;
    printf("The sum of %d and %d is %d", Number1, Number2, Sum);
}

Now this program is more interesting. It asks the program user for input. It then assigns the first integer value to Number1:

scanf("%d", &Number1);

Then it asks them for another number and assigns that to Number2:

scanf("%d", &Number2);

Then it adds the two values together and prints out the result:

Sum = Number1 + Number2;
printf("The sum of %d and %d is %d", Number1, Number2, Sum);

But you ask, why does the variable name have a ’&’ in front of it? Well when we’re dealing with scanf() we must preceed the variable name with that ’&’ sign. You must do this because you are storing the input directly into a memory location. For now, just don’t forget the ’&’.

Let’s do it with a char.

#include <stdio.h>

int main()
{
    char Letter;
    printf("Enter a letter:");
    scanf("%c", &Letter);
    printf("Your letter is %c", Letter);
}

scanf()is a very useful function, play around with it for a while, try modifying the program a little, maybe take two letters. When you’re happy continue.


Continue to Variables »
In this tutorial:
  1. What is C?
  2. Control Structures
  3. Arrays
  4. Text Files
  5. Bibliography
  6. Functions & Pointers
  7. Functions
  8. Pointers
  9. Taking Input
  10. Variables
  11. Compilers
  12. Hello World
icons