0

Summing Elements in Array

Hi, I've been doing learning and I have come to encounter this issue. QUESTION : You are given a program that takes the length of the array as the 1st input, creates it & then takes the next inputs as elements of the array. Complete the program to go through the array & calculate the sum of the numbers that are multiples of 4. // I did add a couple of lines so that the programme can get through which i/put is the multiple of 4. However, the results keep showing, the class was not found. Pls, help me. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int length = scanner.nextInt(); int[] array = new int[length]; for (int i = 0; i < length; i++) { array[i] = scanner.nextInt(); } //your code goes here int sum = 0; if (array[i] % 4 ==0);{ sum = sum += array[i];{ System.out.println(sum); } } } }

3rd Aug 2021, 12:54 AM
Nur Ameera Nabila Binti Abdul Rahim
Nur Ameera Nabila Binti Abdul Rahim - avatar
3 Réponses
+ 1
add for() loop delete ; after if () sum += array[i]; //delete one '=sum' and { at the end count { } pairs and consider if it is necessary to use it print result outside if() {} and for() {} ; after if() causes end of if() command and next lines are out of if
3rd Aug 2021, 1:16 AM
zemiak
0
package learningcoding; import java.util.Scanner; public class lesson16arraysumming { public static void main(String[] args) { Scanner read = new Scanner(System.in); int length = read.nextInt(); int[] array = new int[length]; int sum = 0; int sum2 = 0; int n = -1; for (int i = 0; i < length; i++) { array[i] = read.nextInt(); if (array[i] % 4 == 0) { sum += array[i]; } } System.out.println(sum); System.out.println(); /************************************/ while (n < length - 1) { n++; array[n] = read.nextInt(); if (array[n] % 4 == 0) { sum2 += array[n]; } } System.out.println(sum2); } } //either loop works
21st Sep 2021, 7:07 AM
jiaqi chen
jiaqi chen - avatar