Data Types
Data types specifies the type of data to be stored inside a variable. We have seen some data types before like int: which stores integer, string: which can store names or characters.
There are a number of built-in data types in C++. We are going to look at all of them.
- int : It can store integer numbers both positive and negative. Integer means without the decimal point. Eg. 0,-56,78 etc.
- float : It can store number including decimal numbers too. Eg. 6.78,-67.9 ,0.4 etc. But float cannot store decimal number having large values after the decimal.
- double : It also store decimal values and can store larger value.
- char : This data type stores only one character. Eg. ‘a’, ‘b’ , ‘c’ etc/
- string : String are composed of characters, numbers and symbols. Eg. “Programming
“, “star” etc.
The data storing capacity of int, float can be modified using modifiers. The modifiers are:
- signed: A signed integer can hold both positive and negative values.
- unsigned: An unsigned integer can hold only positive values.
- short: Short halves the data storing capacity of a data type.
- long: Long doubles the data storing capacity of a data type.
This modifiers are used before the variable name. For example:
unsigned long int a;
We usually find use of long when we want to store big integers. Other modifiers are not used so often.
Array
Arrays are used to store collection of values having same data type. Instead of using multiple variables, we can use an array to store all of them. For example:
int a[5];
This declares an array of size 5 which can store integer values. We can also give value to the array at the time of declaration. For example:
int b[5] = {2,5,6,7,4};
An element of an array can be accessed using [] (square bracket).
int a[4] = {2,3,4,5};
cout<<a[0];
//outputs 2
cout<<a[1];
//outputs 3
One important thing to note here is that the indexing of an array starts with 0(zero) and end at (n-1) where n is the size of the array.
Thus an element at 3rd position can be accessed by a[2].
As array is a collection of values, we usually need to loop over elements of array to modify them or to make use of them. We can iterate over the elements of an array using a for loop. For example:
int a[4] = {1,2,3,4];
for(int i = 0; i<4; i++) {
cout<<a[i]<<endl;
}
Output will be:
1
2
3
4
We can also change or assign the value of an element of an array by:
#include <iostream>
using namespace std;
int main()
{
int a[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
cout<<a[1]<<endl; //outputs 2
a[1] = 4;
cout<<a[1]; //outputs 4
}
This is enough as an introduction to arrays. We will explore some more uses of arrays latter on.
