Tuesday, 9 December 2014

Application of Reverse number

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

  For Exp: 

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


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

  27.     public static int ReverseNumber( int digit )  
  28.  
  29.     {  
  30.         int x,reverse=0;  
  31.           
  32.         while(digit !=0)  
  33.         {  
  34.             x=digit%10;  
  35.             reverse=reverse*10+x;  
  36.             digit=digit/10;  
  37.         }  
  38.         return (reverse);  
  39.     }  
output of application of reverse a number
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.