0
Where is the mistake
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++){ array[i] = scanner.nextInt(); int divisible=(array[i]%(4) ); if (divisible ==0){ sum =sum+array[i]; System.out.println(sum); } } //your code goes here; } }
6 Réponses
+ 1
I am not sure what your code is supposed to do. Has it to print just one value. If so, your print statement is now in the for loop and in the if statement, it should then be after it.
0
Please add Java to the thread's tags for improved clarity on language context.
https://code.sololearn.com/W3uiji9X28C1/?ref=app
0
Achraf Soua
No mistakes just print sum outside the loop
0
Thanks AJ- SoloHelper
But I want to understand and i want an explanation of
sum=sum+array[i];
Why we don't put sum=array[i];
0
Achraf Soua you don't put sum=array[i] because you want to add value of array[i] to existing value of sum. Like, if sum is 1 and array[i] is 2 then sum is 3. This same can also be written as sum+=array[i]
0
Achraf Soua
sum = array[i];
Here just new value will be assign to sum but we have to add each value of array to sum so here sum = sum + array[i] is required.
After every iteration new value will be add to previous sum.
You can understand through this example:
1 + 2 + 3 + 4 + 5
sum = sum + 1; first time sum is 0 so
sum = 0 + 1 = 1 now sum is 1
Again sum = sum + 2
sum = 1 + 2 = 3
Again sum = sum + 3
sum = 3 + 3 = 6
Again sum = sum + 4
sum = 6 + 4 = 10
Now atlast sum = sum + 5
sum = 10 + 5 = 15
Now final sum is 15
See here everytime I am adding new value to previous sum.