C++ program to print value stored in a variable

In this program we will learn how to print the value stored in a variable in C++.

Example 1 – Initializing variable manually

#include<iostream>
using namespace std;
int main()
{
     int x = 7;
     cout<<x;
     return 0;
}

Output

7

Explanation:-

  • The first line is written to include the standard library iostream so that we could use cout and cin statements in our program.
  • The next line specifies that we are using the std(stands for standard) namespace, so as to make all the things available residing in the std namespace in our program without having to use the prefix std. I’ve explained this thing in the previous programs as well.
  • Inside the main function, we have declared a variable x of integer type and initialised it with a value 7.
  • In the next line we have displayed the value contained by the variable x by the cout statement.
  • return 0, as usual is the exit status of our program (As we have declared the main function as int and not void).

Example 2 – Taking input from the user

#include<iostream>
using namespace std;
int main()
{
    int x;
    cout<<"Enter a number";
    cin>>x;
    cout<<x;
    return 0;
}

In this example we have taken the value of the variable x by a user instead of initializing it manually. We have done it by the cin statement.

When this program is executed, the user would see a message saying “Enter a number”, and when a number is entered, it stores in the variable x. After that, the stored value is displayed by the cout statement.

Note: The ‘cout’ statement is used to display something while the ‘cin’ statement waits for a value to be input and stores  the value in the specified variable.