Site icon i2tutorials

CPP- Variables

Variables

 

Declaration of Variables:

All variables need to be declared prior to use in the program. Provided unlike in C, in C++ you can declare the variables whenever there is a need for you anywhere in the program even between the statements also.

 

Example Program:

Program to find sum and average of two numbers.

#include<iostream>
using namespace std;
int main()
{
float num1, num2; //declaration of variables
cout<<"Enter two numbers:";
cin>>num1;
cin>>num2;
float sum; //declaration
sum=num1+num2;
cout<<"Sum is:"<<sum;
float average; //declaration
average=sum/2;
cout<<"\nAverage is:"<<average;
return 0;
}

 

Output:

 

Note: The only disadvantage of this style of declaration is that we cannot see all the variables used in a program at a glance.

Exit mobile version