Can you please check my code. I think the logic is fine
Code not working
import java.util.Scanner; public class triplets { public static void main(String[] args) { Scanner scn=new Scanner(System.in); int n = scn.nextInt(); int car = 0; int sum1=0,sum2=0; for(int i=1;i<=n;i++) { car= scn.nextInt(); } while(car>0) { int d=car%10; if(d%2==0) { sum1=sum1+d; car=car/10; if(sum1%4==0) { System.out.println(βYesβ); } else { System.out.println(βNoβ); } } else { sum2=sum2+d; car=car/10; if(sum2%3==0) { System.out.println(βYesβ); } else { System.out.println(βNoβ); } } } }}
@rg361 the code you sent is in unreadable form can you please submit the code once(So that I will get the code) or try to upload this code to ide.codingblocks and save the code and share the link with me.
@rg361 When you are checking if sum1%4 == 0 this condition should be checked outside the while loop bcoz we have to check the overall sum of even digits and we will get overall sum after the while loop ends and the same applies to sum2%3 == 0 should be outside the while loop.
Note : reinitialize sum1 and sum2 after every query like sum1 = 0 sum2 = 0 ;
Corrected Code is below :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int car = 0;
int sum1 = 0, sum2 = 0;
for (int i = 1; i <= n; i++) {
// reinitialize
sum2 = 0;
sum1 = 0;
car = scn.nextInt();
while (car > 0) {
int d = car % 10;
if (d % 2 == 0) {
sum1 = sum1 + d;
car = car / 10;
} else {
sum2 = sum2 + d;
car = car / 10;
}
}
// if condition outside for loop
if (sum1 % 4 == 0 || sum2%3 == 0) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
Got it. It worked. Thanks
I hope Iβve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.