Hi guys.... What am I missing on my code.i want to return 1 if all the numbers are divisible by two and return 0 if not all | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Hi guys.... What am I missing on my code.i want to return 1 if all the numbers are divisible by two and return 0 if not all

public class Program { public static void main(String[] args) { int div=1; int nodiv=0; int [] arr={2,6,8}; for (int i=0;i<arr.length;i++ ){ if (arr[i]/2) { return div ; else if (arr[i]!/2); return nodiv; } } } }

27th Feb 2017, 4:30 PM
Ricardo Chitagu
Ricardo Chitagu - avatar
7 Answers
+ 3
you have to use modulo% to check if the reminder of the division by 2 is 0 (even number) or not (oddnumber) if (arr[i]%2==0){ return div; } else{ return nodiv; }
27th Feb 2017, 4:37 PM
seamiki
seamiki - avatar
+ 3
instead of returning, store the result of every for iteration in an array String [] results ={0,0,0}; for (int x=0; x<arr.length;x++){ if(arr[i]%2==0){ results[x] = "no div"; }else{ results[x] ="nodiv"; } output the content of the array after the for loop
27th Feb 2017, 7:06 PM
seamiki
seamiki - avatar
+ 2
you are performing a return on the first check reguardless of the outcome. KO what you want to do is return 0 when one doesn't match or get to the end and return 1 when the loop has ended. int div=1; int [] arr={2,6,8}; for (int i=0;i<arr.length;i++ ){ if (arr[i]!/2){ div=0; break; } } return div; it would also be better to use 1 variable and just set it to 0 it the divide fails and simply return it at the end again
27th Feb 2017, 4:41 PM
Aaron Gibson
Aaron Gibson - avatar
+ 2
if (arr[i]!/2) is wrong if (arr[i]%2 >0) is what you need
27th Feb 2017, 11:07 PM
Aaron Gibson
Aaron Gibson - avatar
+ 1
first thing I am noticing is: you are putting if , else if block in one {}, either put in different {} or dont put
27th Feb 2017, 4:45 PM
Raj Kumar Chauhan
Raj Kumar Chauhan - avatar
+ 1
public class Program { public static void main(String[] args) { int div=1; int [] arr={2,6,8}; for (int i=0;i<arr.length;i++ ){ if (arr[i]!/2) { div=0 ; break ; } } return div; } } } OK tried this one Arron... not running and I've tried yours seamiki not running as well
27th Feb 2017, 4:51 PM
Ricardo Chitagu
Ricardo Chitagu - avatar
+ 1
c# code looks like public class Program { static bool DivisibilityChecking(int[] arrr) { for (int i = 0; i < arrr.Length; i++) { if (arrr[i] % 2 == 0) { return true; break; } } return false; } static void Main(string[] args) { int[] arr = { 9, 15, 2 }; Console.WriteLine(DivisibilityChecking(arr)); } } }
27th Feb 2017, 4:56 PM
Tony Loa
Tony  Loa - avatar