Monday 5 December 2016

Reverse n numbers of a integer Array

Input: n, int[] array
For example n=2 , array = {2,3,4,5,6,7}

Output: 3,2,4,5,6,7 Explanation - just reverse first 2 elements remaining will same.

int n = Convert.ToInt32(Console.ReadLine());
            int[] arr = new int[] {2,3,4,5,6,7,8 };

            int[] revarr = new int[arr.Length];

            for(int i = 0; i < n; i++)
            {
                revarr[n - i-1] = arr[i];
            }

            for(int i = n; i < arr.Length; i++)
            {
                revarr[i] = arr[i];

            }

1 comment:

  1. Why don't you use Array.Reverse(arr, 0, 2) ?

    Why do you create a new array (revarr) when it consumes memory?

    ReplyDelete

Note: only a member of this blog may post a comment.