Home » .Net

Reverse array elements using c# program

In this C# program, we will learn how to reverse an array of integers? here we are taking integers and then reversing all elements.

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

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.