05 – C++ : Variables

0
62

CplusplusIn C++, each variable has a specific type wherein it determines the layout of the variable’s memory and the size. Not just that, it also determines the range of values stored within that memory.

 

Variable can be consist of characters such as digits, letters, and even an underscore. It either begins with a letter or a digit. And because C++ is case-sensitive, the use of lowercase and uppercase are very distinct.

 

Below are the basic types of variable in C++:

 

Type Description
bool provide the true and false value
char it hold one character only either string and integer and etc.
int set numbers only
float determine numbers with the decimal point
double determine numbers with the decimal point
void Does not return any value.
wchar_t contains wide character type.

Example:

  • int i;
  • char name;
  • float total;
  • double amount;
  • bool result;

Executed program

for int

#include <iostream>

using namespace std;

int main()
{

 int i=9;

 cout << "The number is " << i << endl;
 return 0;
}

for char

#include <iostream>

using namespace std;

int main()
{

 char fname[] = "janobe";

 cout << "My name is " << fname << endl;
 return 0;
}

for float

int main()
{

 float total;

 total = 2.4 - 2;

 cout << "The answer is " << total << endl;
 return 0;
}

for double

#include <iostream>

using namespace std;

int main()
{

 double total;

 total = 3.4 - 2;


 cout << "The answer is " << total << endl;
 return 0;
}

for bool

#include <iostream>

using namespace std;

int main()
{

bool result;

 cin >> result;

if(result == true){
 cout << "The result is true" << endl;
}else{
 cout << "The result is false" << endl;
}

 return 0;
}

 

C++ variable can also be declare in a group and its seperator is a comma(,).

Example

#include <iostream>

using namespace std;

int main()
{

int a= 2 , b = 4, c = 6;

string name = "Janobe", address = "Kabankalan City";

//for integers
 cout << "a = " << a << endl;
 cout << "b = " << b << endl;
 cout << "c = " << c << endl;

 //for string
 cout << "name = " << name << endl;
 cout << "address = " << address << endl;

 return 0;
}

Note : when declaring a variable, you have to put a correct name for the action you want to perform to avoid misdirection.

Facebook Comments
(Visited 75 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here