Variables Declaration:
Declaring a variable is assigning it data type to that variable.
Syntax:
DATA_TYPE VARIABLE_NAME ;
Examples:
int num1, num2;
double sale;
char first;
string str;
int first, second;
char ch;
double x;
Variable Initialization:
Assigning value to the variable is called variable initialization.
Syntax;
DATA_TYPE VARIABLE_NAME = VALUE ;
Examples:
Now consider the following assignment statements:
num1 = 4;
num2 = 4 * 5 – 11;
sale = 0.02 * 1000;
first = ‘D’;
str = “It is a sunny day.”;
int first = 13, second = 10;
char ch = ‘ ‘;
double x = 12.6;
Practice Program:
The following C++ program shows the effect of the preceding statements:
// This program illustrates how data in the variables are
// manipulated.
#include
#include
using namespace std;
int main()
{
int num1, num2;
double sale;
char first;
string str;
num1 = 4;
cout << “num1 = ” << num1 << endl;
num2 = 4 * 5 – 11;
cout << “num2 = ” << num2 << endl;
sale = 0.02 * 1000;
cout << “sale = ” << sale << endl;
first = ‘D’;
cout << “first = ” << first << endl;
str = “It is a sunny day.”;
cout << “str = ” << str << endl;
return 0;
}
Sample Run:
num1 = 4
num2 = 9
sale = 20
first = D
str = It is a sunny day.