LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 19

Rotating an array to the right by k positions Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6};
        int k = 8;
        int n = a.length;
        int[] r = new int[n];
        for (int i = 0; i < n; i++) r[(i + k) % n] = a[i];
        System.out.println(Arrays.toString(r));
    }
}
  • A [5, 6, 1, 2, 3, 4] Correct
  • B [3, 4, 5, 6, 1, 2]
  • C [6, 1, 2, 3, 4, 5]
  • D ArrayIndexOutOfBoundsException
Correct Answer: Option A

Rotating by 8 on 6 elements is the same as rotating by 2; % n wraps indexes around.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links