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
