1. Consider the following 1 dimensional array.int[] N[4] ={5,6,8,1,2};state the value for
I) N[0
]II) N[1
III) N[2]
2. Write program statements that will do the following to array X shown below: -
int[] X= new int[20];
for(i=0;i<=19;i++)
X[i]=i;
I. Print all elements (use loop).
II. Replace third elements with 7.
III. Copy the elements in the fifth location into the first one.
IV. Increase the sixth element by 2.
V. Find the sum of the first nine elements.
VI. Multiply each of the first six elements by 2 and place each product in an element of the array named SecondArray.
VII. Display all even-numbered elements.
for(?;?;?) {
System.out.println(X[i]);
}
3. Read 10 score and find how many score above the average.
int[] score[ 10 ] = { 4, 1, 5, 3, 4, 10, 9, 2, 1, 7 };
find the maximum value in array score. An algorithm for finding the maximum value is as follows:-
1. Assume that the first element is the largest so far and save its subscript as the subscript of the largest so far.
2. For each array element do
If the current element is > than the largest so far then
save the subscript of the current element as the subscript of the largest so far.
Solution (part of) question 2.
import java.util.Scanner;
public class demoarray2 {
public static void main(String[] args) {
int[] x = new int[10];
int i;
for(i=0;i<=9;i++){ // jana nombor rawak dan simpan dalam array x
x[i]= (int)(Math.random()*101);
}
//II. Replace third elements with 7.
x[2]=7;
//iii. Copy the elements in the fifth location into the first one
x[0]=x[4];
//IV. Increase the sixth element by 2.
x[5]=x[5]+2;
for(i=0;i<=9;i++){ // lihat nilai dalam array x
System.out.println(x[i]);
}
//V. Find the sum of the first nine elements.
int sum=0;
for(i=0;i<=8;i++){ // gantikan ?
sum=sum+x[i];
}
System.out.println("Hasil tambah nilai x pertama hingga 9 ialah:"+sum);
}
//VII. Display all even-numbered elements.
for(i=0;i<=9;i=i+2) { // gantikan ?
System.out.println(X[i]);
}
}
No comments:
Post a Comment