+ 1
Need help with this one
I'm suppose to sum up number only multiple of 4 with if statement 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]; int sum=0; for (int i = 0; i < length; i++) { sum += array[i]; } //your code goes here
10 Respuestas
+ 6
this is the task description:
You are given a program that takes the length of the array as the first input, creates it, and then takes the next inputs as elements of the array.
Complete the program to go through the array and calculate the sum of the numbers that are multiples of 4.
Sample Input
5
4
9
16
2
7
Sample Output
20
+ 6
sebastien lalloz ,
what you need is:
▪︎a variable that can hold the running total that has to be calculated
▪︎a for- each loop (a simplified for-loop) like:
for (type var_name : array_name) {
- use if statement to check if var_name is divisible evenly by 4
- if yes, add variable to the total
}
▪︎after the loop is done, output the content of the variable that holds the total
+ 4
have a look st the file. please try to understand how it works:
https://code.sololearn.com/cq7BUkan63AW/?ref=app
+ 1
Are you supposed to read in the values for <array> elements? as I understand it, <array> contains <length> elements initialized by zero until they are assigned other value.
+ 1
It's the summing array in the array portion of the Java course
+ 1
Can you copy/paste the main part of the task Description? I just need to be sure that I understood you correctly ...
+ 1
Thx
+ 1
Thx so much for the help guys. But didn't cover the for each loop yet...
0
This is the start code for the task
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();
}
0
I'm still having problems with the for loop and the if statement. This is what I have so far.
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;
for (int sum : new int );
if (int i %=4);
{System.out.println(sum);}