Challenge: Filtering Numbers in a Loop
Oppgave
Swipe to start coding
Find the sum of all numbers from 1 to n
, excluding those that are divisible by 3 or 5.
- Create a method called
sumNotDivisibleBy3Or5(int n)
that returns anint
. - Inside this method, create a
for
loop that iterates from 1 ton
(inclusive). - In each iteration, check if the number is not divisible by 3 and not divisible by 5.
- If the number passes the condition, add it to a running total
sum
. - Return the total
sum
after the loop ends.
Løsning
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.example;
public class Main {
public static int sumNotDivisibleBy3Or5(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
if (i % 3 != 0 && i % 5 != 0) {
sum += i;
}
}
return sum;
}
public static void main(String[] args) {
int n = 15;
int sum = sumNotDivisibleBy3Or5(n);
System.out.println("The sum of numbers from 1 to " + n + " that are not divisible by 3 or 5 is: " + sum);
}
}
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 3. Kapittel 8
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.example;
public class Main {
public static int sumNotDivisibleBy3Or5(int n) {
int sum = 0;
for (___) {
if (___) {
sum ___;
}
}
return sum;
}
public static void main(String[] args) {
int n = 15;
int sum = sumNotDivisibleBy3Or5(n);
System.out.println("The sum of numbers from 1 to " + n + " that are not divisible by 3 or 5 is: " + sum);
}
}
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår