Array Initialization
It is a simple method to initialize an array, whether One-Dimensional or Two Dimensional.
The values given in the brackets is separated by the comma. All the elements in the list will have the same base type because as you know an array consists of elements of same type of elements whether float, int,etc.
Syntax: type array_name[size]={values_list};
Example:
int num[6]={23,56,12,81,10,1};Now the values would be assigned like:
num[0] =23;
num[1] =56;
num[2] =12;
num[3] =81;
num[4] =10;
num[5] =1;
Two Dimensional arrays are also initialized in the same manner.
Syntax: type array_name[size][size]={values_list};
Example:
int matrix[3][3]={1,2,3,4,5,6,7,8,9};Now the values would be assigned like:
matrix[0][0]=1;
matrix[0][1]=2;
matrix[0][2]=3;
matrix[1][0]=4;
matrix[1[1]=5;
matrix[1][2]=6;
matrix[2][0]=7;
matrix[2][1]=8;
matrix[2][2]=9;
It can be also be written as
int matrix[3][3]= { 1,2,3,
4,5,6,
7,8,9 };
C++ also allows you to skip the size of the array in initialization statement. The main advantage of not declaring the size is that we can increase or decrease the value_list without changing dimensions.
Example: int square[]={2,3,4,5};
char name[]="User";
No comments:
Post a Comment