cin and cout

For any programming language, two of the most important operations are its input and output operations. In our first program, we used output operator to print hello world. In this article, we will study about both the operators and write a program that inputs a value and provides a proper result using the output operator.

Getting an input is nearly similar to getting an output in C++. We have different signatures for each of the operators. >> is the input operator and << is the output operator. We use cin for inputting the value and cout for outputting the value. For instance,

cin>>a;
cout<<"This is cout";

So the first line of code will ask the user to input the value. Now depending on the data type of a, the value will be assigned to a. If a is an integer type, the value that will be demanded will be integer type and that value will be assinged to a.

After you enter the value and hit enter, the cout operator will work and will print the line “This is cout”. We can see the output of the program below.

5
This is cout

You can always insert the value in the variable, do some operations and output the demanded result. Let us make a program that inputs principal amount(P), rate of interest(R) and time(T) and calculate the simple interest on our money.

In this case, our inputs and output variables are

  • Principal amount – p
  • Interest rate -r
  • Time – t
  • Output – o
#include<iostream>
using namespace std;
int main(){
		
	int p,r,t,o;
	/* here we are considering all of our 
	variables as integer data types*/
	cout<<"Welcome to SI calculator"<<endl;
	cout<<"Enter your principal amount"<<endl;
	cin>>p;
	cout<<"Enter your interest rate"<<endl;
	cin>>r;
	cout<<"Enter the time in years"<<endl;
	cin>>t;
	//formula for interest rate 
	o = p+p*r*t/100;
	cout<<"Your SI is "<<endl;
	cout<<"SI : "<<o<<endl;
	return 0;
}

The output of the program is

Welcome to SI calculator
Enter your principal amount
2000
Enter your interest rate
5
Enter the time in years
3
Your SI is 
SI : 2300

So, there you have it. A simple program that calculates simple interest given proper input parameters. Here are some questions that you can try

Write a program that prints the letter of your initials in a grid of stars. For instance, my initial letter is A.

                            *
                           *  *
                          *    *
                         *      *
                        * * * ** *
                       *          *
                      *            *

Hint: Use cout and spaces

Write a program that outputs the sum of two input numbers.

Write a program that asks your name and responds with hello

Amar//Input
Hello Amar//Output

Hint: Use char we saw in the article

Write a program to see if the input number is odd or even.

Leave a Reply