Simple program #12 (Source code to reverse a
number)
Enter a number: 456
Reverse of 456 is: 654
The program is written in C#
programming language and will accept a number as input. The logic of the
program is to reverse a number.
Let’s find out a simple and easy way
to code the program.
Practical Implementation:
using System;
namespace patternProblem.Simple_program
{
class Simple12 //reverse a number
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
int n = Convert.ToInt32(Console.ReadLine());
int r = 0;
int rev = 0;
int temp = n;
if (n > 0)
{
Console.WriteLine("Reverse of {0} is: {1}", temp,
reverseLogic(n, r, rev));
}
else
{
n = n * -1;
Console.WriteLine("Reverse of {0} is: -{1}", temp, reverseLogic(n, r, rev));
}
Console.ReadKey();
}
public static int reverseLogic(int n, int r, int rev)
{
for (; n > 0; )
{
r = n % 10;
rev = rev * 10 + r;
n = n / 10;
}
return rev;
}
}
}
Output:
The input
number is 456. The program will reverse the input number. The output is shown
below:
Enter a number: 456
Reverse of 456 is: 654
Press any key to continue . . .
For any
query, comment us below.
Skip to
Main Table Simple program
Keep learning and sharing...
No comments:
Post a Comment