Introduction
The first example shows how to reverse a number in C#. The second example shows how to reverse a string in C#.
Reverse a Number in C#
Here is the code sample that shows you to reverse a number in C#.
using System;
namespace ReverseNo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number to reverse");
int Number = int.Parse(Console.ReadLine());
int Reverse = 0;
while (Number > 0)
{
int remainder = Number % 10;
Reverse = (Reverse * 10) + remainder;
Number = Number / 10;
}
Console.WriteLine("Reversed number is {0}", Reverse);
Console.ReadLine();
}
}
}
Output
Reverse a String in C#
The following code sample shows how to reverse a string in C#.
using System;
namespace reverseString
{
class Program
{
static void Main(string[] args)
{
string str = "", reverse = "";
int Length = 0;
Console.WriteLine("Enter a Word");
// Getting String (word) from Console
str = Console.ReadLine();
// Calculate length of string str
Length = str.Length - 1;
while (Length >= 0)
{
reverse = reverse + str[Length];
Length--;
}
// Displaying the reverse word
Console.WriteLine("Reverse word is {0}", reverse);
Console.ReadLine();
}
}
}
Output
Hope you like it. Thanks.