Q:

Reverse array elements using c# program

belongs to collection: C# Basic Programs | array programs

0

Given an integer and we have to find its reverse array.

For example we have an array arr1 which contains 5 elements: 12 14 11 8 23

And we create a temporary array named arr2 with same size. As we know that using Length property we can find length of array. So that we assign last element of arr1 to first position of arr2 and then decrement counter till 0th position. That’s why finally reverse array will be arr2.

After this process:
Arr1:	12 14 11 8 23
Arr2:	23 8 11 14 12

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            int i = 0;
            int j = 0;

            int[] arr1   = new int[5];
            int[] arr2 = new int[5];
            
            //Read numbers into array
            Console.WriteLine("Enter numbers : ");
            for (i = 0; i < 5; i++)
            {
                Console.Write("Element[" + (i + 1) + "]: ");
                arr1[i] = int.Parse(Console.ReadLine());
            }

            //Assign elements of arr1 from last to first element to arr2        
            for (i = 0,j=arr1.Length-1; i < arr1.Length; i++)
            {
                arr2[i] = arr1[j--];
            }

            //Reverse array elements in arr2
            Console.WriteLine("Reverse elements : ");
            for (i = 0; i < 5; i++)
            {
                Console.WriteLine("Element[" + (i + 1) + "]: "+ arr2[i]);
                
            }

            Console.WriteLine();
        }
    }
}

Output

Enter numbers :
Element[1]: 10
Element[2]: 20
Element[3]: 30
Element[4]: 40
Element[5]: 50
Reverse elements :
Element[1]: 50
Element[2]: 40
Element[3]: 30
Element[4]: 20
Element[5]: 10

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | array programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Delete an element from given position from array u... >>
<< Insert an element at given position into array usi...