FREE DOWNLOAD

Array Initialization

Problem:

Write code that fills an array double values[10] with each set of values below.

a. 1 2 3 4 5 6 7 8 9 10
Solution:
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++)
arr[i] = (i + 1);

b. 0 2 4 6 8 10 12 14 16 18
Solution:
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++)
arr[i] = 2 * i;

c. 1 4 9 16 25 36 49 64 81 100
Solution:
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++)
arr[i] = i * i;

d. 0 0 0 0 0 0 0 0 0 0
Solution:
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++)
arr[i] = 0;

e. 1 4 9 16 9 7 4 9 11
Solution:
int[] a = { 1, 4, 9, 16, 9, 7, 4, 9, 11};

f. 0 1 0 1 0 1 0 1 0 1
Solution:
int flag=0;
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++)
{
If(flag==0)
{
arr[i] = 0;
flag=1;
}
else
{
arr[i] = 1;
flag=0;
}
}

g. 0 1 2 3 4 0 1 2 3 4
Solution:
int counter=0;
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++)
{
arr[i] = counter++;
if(counter==4)
counter=0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *



Solutions Authored by 15+ Years Experienced Industry Expert