Basic Input Output in CPP
Basic Input Output in CPP
C++ comes with a library which provides us with many ways for performing input and
output. In C++ input and output is performed in the form of a sequence of bytes or
more commonly known as streams.
• Input Stream: If the direction of flow of bytes is from the device (for example,
Keyboard) to the main memory then this process is called input.
• Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device( display screen ) then this process is called output.
These two are the most basic methods of taking input and printing output in C++. To
use cin and cout in C++ one must include the header file iostream in the program.
I. Standard output stream (cout): Usually the standard output device is the display
screen. The C++ cout statement is the instance of the ostream class. It is used to
produce output on the standard output device which is usually the display
screen.
The data needed to be displayed on the screen is inserted in the standard output
stream (cout) using the insertion operator(<<).
// using cout
#include <iostream>
using namespace std;
int main()
{
cout << "Welcome to CPP";
return 0;
}
Output: Welcome to CPP
In the above program the insertion operator(<<) inserts the value of the string
variable sample followed by the string "Welcome to CPP"; in the standard output
stream cout which is then displayed on screen.
II. standard input stream (cin): Usually the input device in a computer is the
keyboard. C++ cin statement is the instance of the class istream and is used to
read input from the standard input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs.
The extraction operator extracts the data from the object cin which is entered
using the keboard.
#include <iostream>
using namespace std;
int main()
{
int age;
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is: " << age;
return 0;
}
Output: Enter your age: 18
Your age is: 18
1. Simple C++ program to add two numbers
// sum of 2 nos
#include <iostream>
using namespace std;
int main()
{
int num1, num2;
cout<<"Enter first integer number: ";
cin>>num1;
cout<<"Enter second integer number: ";
cin>>num2;
cout<<"Sum of entered numbers is: "<<num1+num2;
return 0;
}
Output:
Enter first integer number: 10
Enter second integer number: 20
Sum of entered numbers is: 30
#include <iostream>
int main()
{
return 0;
}
Output:
Enter first number: 21
Enter second number: 19
Sum=40