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
import java.io.*;
class GFG {
public static void main(String[] args)
{
Integer[] array = new Integer[ 5 ];
for (Integer p : array) {
System.out.print(p + " " );
}
}
}
|
Python3
arr = [ None ] * 5
print (arr)
|
Output
null null null null null
1.2. If the array elements are of primitive data types then the default value is 0.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int [] array = new int [ 5 ];
for ( int p : array) {
System.out.print(p + " " );
}
}
}
|
Python3
C#
using System;
public class GFG
{
static public void Main (){
int [] array = new int [5];
foreach ( int p in array)
{
Console.Write(p + " " );
}
}
}
|
2. Garbage value:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int array[5];
for ( int p : array)
cout << p << " " ;
return 0;
}
|
Output
4196608 0 4196144 0 -1374567488
Default values in Javascript
Javascript
<script>
let arr = new Array(5);
for (x of arr){
document.write(x + "<br>" );
}
</script>
|
Output:
undefined
undefined
undefined
undefined
undefined
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!