Initialization of array and its types
The process of assigning the values to elements of an array is called an initialization of the array. It can be done by a various method which is explained briefly below with examples.
Element by element
In this case, each and every element of an array is assigned with a value individually.E.g. int a[3];
a[0]=45;
a[1]=7;
a[2]=-4;
Declaration and initialization at the same time
The values are assigned to the array at the time of declaration. The values are assigned collectively within a single statement. The values are assigned by keeping them within curly braces{ } and are separated by commas (,).
E.g.
- int a[3]={45,7,-4};
which gives:
a[0]=45 a[1]=7 a[2]=-4
- int a[3]={5};
which gives a[0]=5 and all the other elements will return a garbage value.
Initialization from the user
In this process, we assign different values to the element as per the choice of the user. A for loop is applied to individually call the elements of the array. The values are assigned as per the user and stored in respective subscripts. Then again a for loop is used and elements are displayed individually on the output screen.
Also, see Input and output of a one-dimensional array
No comments:
Post a Comment