C# - Reverse the numbers in an array (integer array) in a Console App

C# - Reverse the numbers in an array (integer array) in a Console App

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

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create two arrays with same length.
            int[] sequence1 = new int[10];
            int[] sequence2 = new int[10];

            //Check if the lenght of both is same. If not exit right away.
            if (sequence1.Length == sequence2.Length)
            {
                //Populate the 1st array.
                for (int i = 0; i < sequence1.Length; i++)
                {
                    sequence1[i] = i;
                    Console.Write(sequence1[i] + " ");
                }

                Console.WriteLine();

                //Take two initialization variables in for loop
                //One variable to iterate through the 1st array. Initialize it to zero.
                //Second variable is to iterate through the 2nd array. Initialize it to the last element of 2nd array.
                //Take the first element in array 1 and assign it to last element in second array.
                for (int i = 0, j = sequence2.Length - 1; i < sequence1.Length; i++, j--)
                {
                    sequence2[j] = sequence1[i];
                }

                //The above mentioned code can be written this way as well.
               
                //for (int i = 0; i < sequence1.Length; i++)
                //{
                //    sequence2[(sequence1.Length-1) - i] = sequence1[i];
                //}

                for (int i = 0; i < sequence2.Length; i++)
                {               
                    Console.Write(sequence2[i] + " ");
                }
            }
            else
            {
                Console.WriteLine("Array length not matching");
                return;
            }
            Console.ReadLine();
        }
    }

}

Output:

No comments: