Computer Science, asked by minhokithiccthighs, 4 months ago

What is the difference between these two statements:
i. int sum[]=new int[10] ii. sum[1]=10;

Answers

Answered by nitinmishra5452141
2

Answer:

int[] z = new int[10]; - This line will make an array of 10 integers. z[0] = 50 ... Similary in the second iteration, the value of 'i' will be 1 and 'z[i]' will be 'z[1]'It looks similar to defining a variable and actually it is. Here we are declaring 10 variables at one go.Normally, we declare and assign a value to a variable as follows.

int x;

x = 50;

For an array, we do the same as follows.

int[] z = new int[10];

z[0] = 50;

int[] z = new int[10]; - This line will make an array of 10 integers.

z[0] = 50; - z[0] represents the first element of the array 'z' and a value of 50 is assigned to it. So, the first element (z[0]) of the array has value 50.

z[0],z[1]....,z[9] are similar to variables we have used before. So, to access an element of an array, we write its index in brackets '[ ]' after the array name i.e. array_name[index].

Thus, for the above example, z[0] is the first element of the array 'z', z[1] is the second element and so z[9] is the tenth element.

And z[0], z[1], ... , z[9] are now same as the variables we have already used.

One more declaration

If we know the elements of an array, then we can also declare the array and assign values to the its variables as:

int[] x = {23,32,43,12,43};

Here, we have declared 'x' with its elements. 'x' will automatically become an array of 5 elements as there are 5 elements in 'x'.

The value of the first element (x[0]) of the array is 23, that of the second element (x[1]) is 32 and thus the value of the fifth element (x[4]) is 43.class A0{

public static void main(String[] args){

int[] z = new int[10];

z[0] = 223;

z[1] = 23;

int[] x = {23,32,43,12,43};

System.out.println(z[0]);

System.out.println(z[1]);

System.out.println(x[3]);

System.out.println(x[0]);

Similar questions