Guys do I have to enter another array for this code to run properly? I mean to compare with. Feel free to give a better answer | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Guys do I have to enter another array for this code to run properly? I mean to compare with. Feel free to give a better answer

public class Program { public static void main(String[] args) { int[]arr={1,2,3,4,5}; int sum=0; int idx=-1; for (int i=0;i<arr.length;i++){ if (arr[i]==0) { idx =i; } else { sum +=arr[i] ; } } int total=(arr.length+1)*arr.length/2; System.out.println ("missing number is "+(total-sum )+" at index "+idx ); } }

3rd Mar 2017, 9:04 AM
Ricardo Chitagu
Ricardo Chitagu - avatar
4 Answers
+ 4
Well, you need to have ( declare ) two arrays: the reference, and the one to be tested. Iterate over one of them, as you've still done, but in place of comparing each element to zero, test if they are in the other array and take a count/list of the results... To perform this test, do it yourself: I haven't enough skill in Java ( ? you didn't even specify for what language you need help ^^ ) and time to lose for doing it for you in an accurate way :P
3rd Mar 2017, 3:07 PM
visph
visph - avatar
+ 3
What would you compare? The only thing you compare in this code, is if each item of your array is equal to zero... I'm not understanding what is your purpose with your next calculations, neither what you expect related to your final output about a "missing number" :P
3rd Mar 2017, 2:20 PM
visph
visph - avatar
+ 1
sorry visph ...lemme explain in detail. I want this code for example to have an array of let's say 10 elements{1,2,3,4,5,6,7,8,9,10}. if I've put an array like this {1,2,3,4,8,9,10} the code shud be able to output the "missing number is 5,6,7".I hope m clearer now.
3rd Mar 2017, 2:46 PM
Ricardo Chitagu
Ricardo Chitagu - avatar
+ 1
oh well.... thanx anyway
3rd Mar 2017, 3:09 PM
Ricardo Chitagu
Ricardo Chitagu - avatar