C++ Variables and Input-Output Operator

September 17, 2015 Posted by WithU Technologies
Let us consider a slightly more complex C++ program. Assume that we would like to read two numbers from the keyboard and display their average on the screen.

#include <iostream>
using namespace std;

int main(){
 
float n1, n2, sum, avg;


cout<<"Enter two numbers"<<endl;

cin>>n1; //Reads first number

cin>>n2; // Reads second number

sum=n1+n2; // Sum of those two number

avg=(n1+n2)/2; //Average of those two number

cout<<"The sum of two numbers is "<<sum<<endl; // Output the summation value

cout<<"The average of two number is "<<avg<<endl; // Output the average value

return 0;


}

Variables
  • The program uses four variables n1, n2, sum, and average.
float n1, n2, sum, avg;
  • The variables are declared as float variables.

  • Variables must be declared before we start a program.

Input Operator

cin>>n1; //Reads first number

cin>>n2; // Reads second number

  • Pronounced as "See-in".

  • These cin operator is used to take input from the user by using those predefined variables.

  • Input statement causes the program to wait for the user to type in a number.

  • The operator » is known as extraction or get from operator.

  • It extracts (or takes) the value from the keyboard and assigns it to the variable on its right.

Cascading of I/O Operators results.

cout<<"The sum of two numbers is "<<sum<<endl; // Output the summation value

cout<<"The average of two number is "<<avg<<endl; // Output the average value

  • As we know cout displayed a message.

  • Here cout display the string
    "The sum of two numbers is "
    and after that in the same line it
    also display the float variable value of sum.

  • Finally, it sends the end line character so that the next output will be in the new line.

  • The multiple use of « in one statement is called cascading.

  • When cascading an output operator, we should ensure necessary blank spaces between different items.

Cascading Output Operator

Using the cascading technique, the last two statements can be combined as follows:

This is one statement but provides two lines of output. If you want only one line of output, the statement will be:

cout<<"The sum of two numbers is "<<sum<< "," // Output the summation value


<<"The average of two number is "<<avg<<endl; // Output the average value


Cascading Input operator

We can also cascade input operator » as shown below:

cin » n1 » n2;

The values are assigned from left to right.

That is, if we key in two values, say, 15 and 30, then 15 will be assigned to n1 and 30 to n2.