As the array is an important data structure for the coding perspective, there are some conditions that need to be careful. As in any language, there are two different methods to initialize the array:
- While declaring the array
- Any time after declaring the array
Shown below are the two ways of initializing an array
Initializing the array at the time of declaration:
Syntax
int arr[] = {1, 2, 3, 4, 5};
Initializing the array after declaration:
Syntax
int arr[5];
for (int i = 0; i < 5; i++)
arr[i] = i + 1;
Why is there a need to initialize an Array?
If the array is not initialized at the time of declaration or any time after that then it will contain some random values in each memory position. These random values can be of two types:
1. Default values.
1.1 If the array elements are of object types then the default value is null.
Java
|
null null null null null
1.2. If the array elements are of primitive data types then the default value is 0.
Java
|
2. Garbage value:
C++
|
4196608 0 4196144 0 -1374567488