C program to print a number stored in a variable

In this program we will see how we can print the value stored in a variable.

To understand this program you should have the knowledge of following topics in C:

  • variables
  • output functions

Program

#include<stdio>
int main()
{
    int a = 4;
    printf("The number is %d", a)
    return 0;
}

Explanation

  • By now, you have understood what a preprocessor directive is. If you don’t, see the first program that print the message “Hello World” or visit this link. C Program to print Hello World
  • Like every C program, this program also starts with the main function. The parenthesis { and } represents the starting and ending of the function.
  • Inside the main function we have declared a variable named ‘a’ which is of type int. This means this variable can store only integer type values. We have assigned a value 4 to this variable at the time of declaration.
  • The print function is a standard C function which is used to print output on to the screen. Inside this function, we have passed two arguments. The first argument is a message along with the format specifier. The format specifier specifies that of which type the value is being stored by the variable. %d is used for the integer type values, for float values we use %f. The second argument is the variable that is holding the particular value.
  • return 0 is the exit status of the program. At this point the program ends. When you would get enough  knowledge about functions, you will understand the return type of functions.

Program by taking input from a user

Now let us try to make the same program by taking input from the user, storing it in the variable and printing it on the screen.

#include<stdio>
int main()
{
    int a;
    printf("Enter a number");
    scanf("%d", &a);
    printf("The number is %d", a)
    return 0;
}

This program also works the same as the upper one. The only difference here is that we are taking the input from the user by the scanf() function. Here scanf() function is accepting two arguments. The first one is the format specifier about which have seen earlier. The second argument &a represents the memory address allocated to the variable a. So whatever value the user enters, it will get stored at the address of a.