C++ Program to Print Number Entered by User

C++ProgrammingServer Side Programming

The objects “cin” and “cout” are used in C++ for input and output respectively. cin is an instance of the istream class and is attached to the standard input device such as the keyboard. cout is an instance of the ostream class and is connected to the standard output device such as the display screen.

A program that prints the number entered by the user is as follows −

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int num;
   cout<<"Enter the number:\n";
   cin>>num;
   cout<<"The number entered by user is "<<num;
   return 0;
}

Output

Enter the number: 5
The number entered by user is 5

In the above program, the user enters the number using the cin object.

cout<<"Enter the number:\n";
cin>>num;

Then the number is displayed using the cout object.

cout<<"The number entered by user is "<<num;

A way for the user to enter multiple numbers is to use an array. This is demonstrated using the below program −

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a[5],i;
   cout<<"Enter the numbers in array\n";
   for(i=0; i<5; i++)
   cin>>a[i];
   cout<<"The numbers entered by user in array are ";
   for(i=0; i<5; i++)
   cout<<a[i]<<" ";
   return 0;
}

Output

Enter the numbers in array
5 1 6 8 2
The numbers entered by user in array are 5 1 6 8 2

In the above program, a for loop is used to access all the array elements from the user. For each iteration of the for loop, the array element with the corresponding index is accessed using the cin object.

for(i=0; i<5; i++)
cin>>a[i];

After that, all the array elements are displayed using the same concept of the for loop.

for(i=0; i<5; i++)
cout<<a[i]<<" ";
raja
Published on 26-Sep-2018 12:36:09
Advertisements