Monday, December 8, 2014

C++ Variables and Data Types

  No comments    
categories: 

C++ Variables and Data Types

A Variable is what the program used to store  value in computer's memory temporarily.
The value stored in a memory location is cleaned wen the program that uses it terminates.

Data Types

Data types of variable tell the computer to store different types f value such as number, text, true/false. etc.
They also inform the computer to reserve the different memory's spaces for those variables.
Here is a table of the data type of variables that can be used:


Declaring variables

In C++ before you can use a variable to store any value. it must be declared.
To declare a variable in C++ you must write down its name immediately after its data type.

Example:

int a;//declare a variable named a to store an integer value
You can declare more than one variables of the same type on a single line by separating them with commas.

Example:
 int a,b;

Assigning values to variables
Example:
int a=10;
char c='a';
bool b=true;

Alternatively, You can write as shown below.

int a;
a=10;
char c;
c='a';
bool b;
b=true;

In C++, A variable can also be a signed variable or an unsigned variable.
Signed means that it can have negative numbers and Unsigned means it can't but unsigned gives a variable a greater positive range.

Example:

unsigned int a;

To give the variable a smaller or bigger range respectively. you need to put short or long keyworks.

Example:

short int a;

String data type

A string is a type of variable that can store multiple words.
You can declare a string in three ways.
The first is to declare it as a string pointer by using *symbol the * means that it points to the first character of the string.

Example:
 char *b;
s="Hello";

The second way is to declare it as an array of characters which you must set size when you declare it.
You have to use the strcpy command to assign values to it.
You must also include the string header file to be able to use the strcpy command

Example:

#include<string>
char s[20];
strcpy(s,"Theara");

The last way is to use the string data type

Example:

string s="C++ Programming";

0 comments:

Post a Comment