I have been trying to get an integer array and it keeps failing. I am trying to find the missing element in an array. Here is my code. What am I doing wrong here?
import java.util.Scanner;
public class GFG {
public static void main(String[] args) {
int T,N,i,j=0,k=1;
int C[]= new int[100];
Scanner sc=new Scanner(System.in);
T=sc.nextInt();
for(i=0;i<T;i++)
{
N=sc.nextInt();
for(j=0;j<N;j++)
{
C[j]=sc.nextInt();
}
while(k<=N)
{
if(k==C[j])
{
k++;
j++;
}
else
{
System.out.println(k);
k++;
j++;
}
}
}
sc.close();
}
}
I trying to find the missing element in a array of integers of consecutive natural numbers
Input:
1 //test cases
4 //array length
1 2 3 5 // array elements
Desired Output:
4
But the output is
1
2
3
4
The comparison is not executing. Why?
On my computer, with the input you mentioned, the program prints the numbers from 1 through 96 and then crashes with a java.lang.ArrayIndexOutOfBoundsException: 100
at the line if(k==C[j])
.
There are a number of potential issues with your code. I’ll mention just two and leave it to yourself to see if you can find more.
for(j=0;j<N;j++)
j
is equal to N
(4 in this case). You need to reset it to 0 before the next loop.k
never becomes 0, so your loop while(k!=0)
runs forever, or more precisely, it runs off the bounds of your array, which causes the crash when you try to access the array element at index 100 (as you know, indices are 0 through 99). You need another way to stop the loop.