DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

How do you reverse a number in C# for loop?

By Ashok Nalam on 18 Jan 2021 | Category: C# | Tagged: array C# reverse for-loop 
In this snippet, we will write a program that reverses an array using for loop in c#.
  Discuss Add Comment   |  
Add rating Rate this resource   

Introduction

In this snippet we will write a program which reverses an array using for loop in c#. 

Example:  If input array is {1,2,3,4,5,6,7} , we should print {7,6,5,4,3,2,1}

From below program using C# for loop, we are basically shifting all array elements from left side to right side.

Program

using System;

namespace DotNetMirror
{
    class ArrayReverseWithForLoop
    {
        static void Main()
        {
            int[] array = { 1, 2, 3, 4, 5, 6, 7 }; //user input
            int arrLen = array.Length;
            int j = 0;
            int[] revArray = new int[arrLen]; //take same length of source array to reverse

            for (int i = arrLen - 1; i >= 0; i--)
            {
                revArray[j] = array[i];
                j++; //increment target array index
            }
            Console.WriteLine("Result: {0}", string.Join(",", revArray));
            Console.ReadKey();
        }
    }
}

Output

Result: 7,6,5,4,3,2,1

Source Code

https://github.com/dotnetmirror/Rev_Array_Using_For_Loop

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9186  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (2)
 
1. By ZAP on 23 Oct 2023

 
2. By ZAP on 23 Oct 2023

 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys