Jindal
Jindal

Reputation: 84

Passing array value to another array in reverse order

I want to pass int a[] values into int b[]. but I'm facing confusion. Can anyone correct me out. The output of b is 0,0,0,45,4,2,1. it supposed to be like 7,6,5,4,45,2,1.

static void Main()
{
    int[] a = new int[] { 1, 2, 45, 4, 5, 6, 7 };
    int[] b = new int[7];
    int temp = 0;

    for (int i = 0; i <= a.Length - 1; i++)
    {
        b[(b.Length - i) - 1] = a[i];

        Console.WriteLine(b[i]);
    }     
}   

Upvotes: 4

Views: 1143

Answers (3)

Reza Aghaei
Reza Aghaei

Reputation: 125197

If you want to create a reverse array from an existing array, you can use Reverse extension method:

//using System.Linq;
int[] a = new int[] { 1, 2, 45, 4, 5, 6, 7 };
int[] b = a.Reverse().ToArray();

You can learn more about Extension Methods.

Upvotes: 5

T.S.
T.S.

Reputation: 19330

You can have this syntax

int[] a = {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[7];

for (int i = 0, j = b.Length - 1; i < a.Length; i++, j--)
{
    b[i] = a[j];
    Console.WriteLine(b[i]);
}

Upvotes: 3

Rufus L
Rufus L

Reputation: 37020

The problem here is that you're inserting items starting from the last index of b, but you're outputting them starting from the first index. The code to copy the items is correct, but you need to adjust your line that outputs the result to the console to show the items in b using the same index that you just used to insert the item.

Note there are a couple of other improvments you can make, such as using array initializer syntax for a, using a.Length to instantiate b instead of a hard-coded number, removing the unused temp variable, using i < a.Length for the for condition (instead of i <= Length - 1, which does a subtraction operation on each iteration), and storing the b index in a variable instead of calculating it twice:

static void Main()
{
    int[] a = new int[] {1, 2, 45, 4, 5, 6, 7};
    int[] b = new int[a.Length];

    for (int i = 0; i < a.Length; i++)
    {
        int bIndex = b.Length - i - 1;
        b[bIndex] = a[i];
        Console.WriteLine(b[bIndex]);
    }

    Console.ReadLine();
}

However, this will still output the items in the order in which you insert them, which will be the same order as they appear in a. If you want to show that the items in b are the reverse of a, the easiest way is to do it after you've populated b. Note we can make use of the string.Join method here to join each item with a comma:

static void Main()
{
    int[] a = new int[] {1, 2, 45, 4, 5, 6, 7};
    int[] b = new int[a.Length];

    for (int i = 0; i < a.Length; i++)
    {
        b[b.Length - i - 1] = a[i];
    }

    Console.WriteLine($"'a' array: {string.Join(",", a)}");
    Console.WriteLine($"'b' array: {string.Join(",", b)}");

    Console.ReadLine();
}

Output

enter image description here

Upvotes: 7

Related Questions