-3

After each loop count and count1 are updated. After giving inputs in Scanner, I'm not getting any output.

Scanner sc = new Scanner(System.in);
int t = sc.nextInt(); // t=1
while (t != 0) {
    int n = sc.nextInt(); // n=5
    int a[] = new int[n]; // a = { 1,2,5,6,7 }

    for (int i = 0; i < n; i++) {
        a[i] = sc.nextInt();
    }
    int count = 0, count1 = 0;
    for (int i = 0; i < n; i++) {
        if ((a[i + 1] - a[i]) > 2) {
            count++;
        } else {
            count1++;
        }
    }
    // this doesn't get printed
    System.out.println(count + 1 + " " + count1);

    t--;
}
3
  • 1
    You only assign a value to t once. If that value is not 0, the loop never ends. Commented Nov 15, 2020 at 7:30
  • Even after adding t--; it shows the same thing Commented Nov 15, 2020 at 7:42
  • Are you sure your program hasn't died with an ArrayIndexOutOfBoundsException? Because the for loop containing it runs until i == n-1, the statement if ((a[i + 1] - a[i]) > 2) (specifically, the a[i+1] bit) will blow up right when i does reach the value of n-1 and the program will have never reached the System.out.println that follows the loop. Commented Nov 15, 2020 at 7:57

3 Answers 3

0

The conditions in the following code block will result in an ArrayIndexOutOfBoundsException as when i = n - 1, if ((a[i + 1] - a[i]) > 2) will try to get an element from a[n - 1 + 1] i.e a[n] which you already know is invalid because the indices in a[] are in the range 0 to n - 1:

for (int i = 0; i < n; i++) {
    if ((a[i + 1] - a[i]) > 2)

You can put it like

for (int i = 0; i < n -1 ; i++) {
    if ((a[i + 1] - a[i]) > 2)

After this correction, given below is the result of a sample run:

1
5
1 2 5 6 7
2 3

It is because count1++ gets executed for 1 2,, 5 6 and 6 7 while count++ gets executed only for 2 5.

Sign up to request clarification or add additional context in comments.

Comments

0
int count=0,count1=0;
for (int i = 0; i < n; i++) 

should be replaced with

int count=0,count1=0;
for (int i = 0; i < n-1; i++) {

You are trying to access n+1 memory location by a[i + 1] which is ArrayIndexOutOfBoundsException.

Comments

0

As you are trying to take continuously for test case input only t-- will not work here. I'm going to post here a generic structure for this. Try the following approach -

public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for(int i = 0; i < t; i++){
            int n = in.nextInt();
            //do your stuff here
            // now you could take input and process them t times
        }

        //finally don't forget to close the input stream.
        in.close();
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.