Unable to write this code properly in eclispe | Sololearn: Learn to code for FREE!

+1

Unable to write this code properly in eclispe

So I have a small project which needs me to make an array with size of 20 and take 20 inputs and then check if all of them are equal using "for" loop. If it is equal it prints equal else it prints broken. I will link the code. Try and run it in and tell me what to change to make it work. Since it's 20 numbers we cant manually check them all so I used the "for(i=0;i<=19;i++)" loop but it isnt working like i intended I used "repeat" to count the number of times it is sucessfully equal and if all no. are equal then the value of repeat will be 20 and then we will check if repeat is 20. if true then all are equal else its not equal the problem is for loop only seems to execute once and so the value of repeat only increases once.

5/6/2019 12:19:46 PM

kuku Debbarma

6 Answers

New Answer

+1

kuku Debbarma You are incrementing the value of i twice, first in num[i++] then as a part on loop increment.So loop will terminate after 10 iteration fix start repeat = 0 loop exit condition should be i<19 if statement if (num[i] == num[i+1] i < 19 not i <= 19 because you are comparing 2 elements at a time. For i = 19, i +1 becomes 20 causing exception, since the highest valid index of array is 19

+1

~ swim ~ i just corrected the loop. Turns out I forgot to edit it after changing the number of integers the array holds but still didn't solve the problem :(

+1

When you do: i = 5; print (num[i++]); It prints num[5] and then add to i so i = 6. Correct code: https://code.sololearn.com/cX4F6GTJ7Ens/?ref=app

+1

Maneren ty for that will definitely give it a look rn

0

https://code.sololearn.com/cctKuIXRL3aM/?ref=app Here is the codd

0

kuku Debbarma Your loop exit condition is i<=3 so it should exit after 4 iterations, but since you are doing i++ inside if, the loop will terminate after 2 iterations The value of repeat will never reach 20. hence if condition after loop fails and prints broken Also remember array indexing starts from 0. And trying to access value beyond the size (no of elements) will result in exception.