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:
- Initialize a variable to store the reversed number (set to zero).
- Loop through each digit of the original number.
- In each iteration, multiply the reversed number by 10 and add the last digit of the original number.
- Remove the last digit from the original number.
- 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.
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:
- Reverse an Array in C# Without Using Reverse Function
- Reverse a String in C# Using a For Loop
- How to reverse string in C# using while loop?
- Add Values to a String Array in C#
- Write A Program To Find Numbers Above And Below The Average In C#
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…