0

My code to access elements of array using for loop. The output of the program is [19,17,15] which are the elements of array int a[] = { 12, 15, 16, 17, 19, 23 }. Output after following code is written:

public class Tester {
    public static void main(String s[]) {
        int a[] = { 12, 15, 16, 17, 19, 23 };
        for (int i = a.length - 1; i > 0; i--) {
            if (i % 3 != 0) {
                --i;
            }
            System.out.println(a[i]);
        }
    }
}

Algorithm:

  1. Iteration 1: i=5 so a[5]=23. "if statement" gets true and --i execute. so i=4. Hence, a[4]=19 will get print as first element in output.

  2. Iteration 2: i=3 so a[3]=17. "if statement" gets true again and --i should execute but it skips that condition as I tried using debugging tool to see how it is working. And output is a[3]=17 which is wrong I think.

Could you help me in understanding why it gives 17 as output? As in my opinion it should skip that part.

5
  • 1
    If i = 3, then i % 3 is 0. That would mean your if statement becomes false and not true. Commented May 13, 2022 at 9:43
  • And since the if statement is false, that would explain the behavior you are seeing. Commented May 13, 2022 at 9:44
  • 1
    Your if statement doesn't check a[i] % 3 != 0 - it checks i % 3 != 0. In the first iteration i is 5 and i % 3 != 0 is true. In the second iteration i is 3 and i % 3 != 0 is false and therefore i is not decremented and a[3] gets printed. Commented May 13, 2022 at 9:45
  • a%b is the modulo operator. It returns the reminder of a/b
    – xImperiak
    Commented May 13, 2022 at 9:48
  • Your problem is that you decrement i twice (once as a result of the condition and again as an an unconditional part of your forloop). Instead replace the if body with continue.
    – Sherif
    Commented May 13, 2022 at 9:53

2 Answers 2

0

Here is a step by step explanation. (i % 3 != 0) checks to see if i is not divisible by 3. Also note that in this context, your post and pre-decrements of i are not relevant as the outcome would be the same no matter how they are decremented.

 i = 5;
 i not divisible by 3 so i-- = 4
 print a[4] = 19
 i-- at end of loop = 3
 i is divisible by 3 so i remains 3
 print a[3] = 17
 i-- at end of loop = 2
 i not divisible by 3 so i-- = 1
 print a[1] = 15
 i-- = 0 so loop terminates.
-1

In iteration 2, where i=3 the condition is false, since 3 % 3 = 0

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented May 14, 2022 at 5:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.