Program for Reverse a Number in C#

Write a program where user gives two inputs digit, the program reverse the inputs and add them and again reverse there sum.

For Example:

Input:

Enter first number: 56
Enter second number:89

Output:

reverse of first number: 65
reverse of second number:98

sum of two reverse no is: 163

reverse of sum: 361

C# Code:

  1. using System;  
  2. public class SumOfDigit  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         int number1, number2;  
  7.         int sum = 0;  
  8.         Console.Write("Enter the first Number: ");  
  9.         number1 = Convert.ToInt32(Console.ReadLine());  
  10.         Console.WriteLine("Reverse of first Number: {0}\n", ReverseNumber(number1));  
  11.         Console.Write("Enter the second Number: ");  
  12.         number2 = Convert.ToInt32(Console.ReadLine());  
  13.         Console.WriteLine("Reverse of second Number: {0}\n", ReverseNumber(number2));  
  14.         sum = ReverseNumber(number1) + ReverseNumber(number2);  
  15.         Console.WriteLine("\n\nSum of Two reverse number is: \t{0}", sum);  
  16.         sum = ReverseNumber((ReverseNumber(number1)) + (ReverseNumber(number2)));  
  17.         Console.WriteLine("Reverse of sum of Two number is: \t{0}", sum);  
  18.     }  
  19.     public static int ReverseNumber(int digit)  
  20.     {  
  21.         int x, reverse = 0;  
  22.         while (digit != 0)  
  23.         {  
  24.             x = digit % 10;  
  25.             reverse = reverse * 10 + x;  
  26.             digit = digit / 10;  
  27.         }  
  28.         return (reverse);  
  29.     }  
  30. }  
Output

program output
Fig: Screenshot of Output

Note: we can also optimize the code by adding a variable reverseSum and store the value of reverse of sum (Line-29) in it.
Ebook Download
View all
Learn
View all