Monday, June 9, 2014

Examples: How to use variables in C++


Example 1: Integer Variables
Syntax: int variable;       //comment

#include <iostream>
using namespace std;
int term;  // term used in two expressions
int main(){
term = 4 * 7; 
cout <<"Twice " << term << " is "<< 2*term <<endl; 
cout <<"Three times " << term << " is " << 3*term <<endl; 
return 0;
}

Example 2: Floating Point Variables
Syntax:  float variable;     //comment

#include <iostream>
#include <conio.h>
using namespace std;
int i;    // an integer variable
float f; // a floating point number 
int main(){
f = 1.0 / 2.0;          // assign floating 0.5 
cout<<" f= "<<f<<endl;
i = 1 / 3;              // assign integer 0 
cout<<" i= "<<i<<endl;
f = (1 / 2) + (1 / 2);  // assign floating 0.0 
cout<<" f= "<<f<<endl;
f = 3.0 / 2.0;          // assign floating 1.5 
cout<<" f= "<<f<<endl;
i = f;                  // assign integer 1 
cout<<" i= "<<i<<endl;
return 0;
}

Example 3: Characters Variables
Syntax:  char variable;   //comment

#include <iostream>
#include <conio.h>
using namespace std;
char c1;  // first character 
char c2;  // second character 
char c3;  // third character 
int main(){
c1 = 'X'; 
c2 = 'Y'; 
c3 = 'Z'; 
cout << c1 << c2 << c3 << " reversed is "<<c3 << c2 << c1 << "\n";
return 0;
}

No comments:

Post a Comment