How to Reverse a Number in C# Using For Loop?

In this C# tutorial, I will explain to you how to reverse a number in C# using a for loop. We will see a complete example that you can run using Visual Studio Windows or a console application.

To reverse a number in C# using a for loop follow the below steps:

  1. Initialize a variable to store the reversed number (set to zero).
  2. Loop through each digit of the original number.
  3. In each iteration, multiply the reversed number by 10 and add the last digit of the original number.
  4. Remove the last digit from the original number.
  5. Continue until the original number becomes zero.

Reverse a Number in C# Using For Loop

First, we need to declare and initialize our variables.

int originalNumber = 12345; // The number to be reversed
int reversedNumber = 0; // The reversed number

We will employ a for loop to reverse the number following the algorithm described above.

for (; originalNumber > 0; originalNumber /= 10)
{
    reversedNumber = (reversedNumber * 10) + (originalNumber % 10);
}

Finally, we will print the reversed number to the console.

Console.WriteLine($"The reversed number is {reversedNumber}");

Here’s the complete C# code to reverse a number using a for loop:

using System;

namespace ReverseNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize variables
            int originalNumber = 12345;
            int reversedNumber = 0;

            // Use for loop to reverse the number
            for (; originalNumber > 0; originalNumber /= 10)
            {
                reversedNumber = (reversedNumber * 10) + (originalNumber % 10);
            }

            // Display the result
            Console.WriteLine($"The reversed number is {reversedNumber}");
        }
    }
}

The output of the program will be:

The reversed number is 54321

You can see the screenshot below for the output after I run the application in a console application.

reverse a number in c# using for loop

I hope you got an idea of how to reverse a number in C# using a for loop with a complete example.

You may also like: