Thursday, June 23, 2022
HomeSoftware DevelopmentWhat occurs Array is just not initialized?

What occurs Array is just not initialized?


Improve Article

Save Article

Like Article

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 + " ");

        }

    }

}

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 + " ");

        }

    }

}

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 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments