+ 4

What the reason for getting the error in it??

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner a = new Scanner(System.in); int x = 0; int b = a.nextInt(); for(int i=0;i<=b;i++) { int c = a.nextInt(); if(c%2==0) { x = x+c; } System.out.println(x); } } }

12th Jul 2021, 4:54 AM
Shahir
Shahir - avatar
4 Respostas
+ 5
Shaik.Shahir There should be i < b instead of i <= b because index start from 0 so if you do <= then you have take one extra input. For example if you takes b = 4 then your other input should be 5 like 1, 3, 5, 6, 7
12th Jul 2021, 5:49 AM
A͢J
A͢J - avatar
+ 4
This code works. In SL Playground you have to set all input data at the start, for example an input can be: 2 1 2 3
12th Jul 2021, 5:52 AM
JaScript
JaScript - avatar
+ 4
Thanks!
12th Jul 2021, 5:53 AM
Shahir
Shahir - avatar
+ 3
Shaik.Shahir Also print statement should be outside loop if you want to get sum of all even number. int x = 0; //b input for (int i = 0; i < b; i++) { //c input if (c % 2 == 0) x = x + c; } System.out.print(x);
12th Jul 2021, 5:52 AM
A͢J
A͢J - avatar