Friday, September 13, 2019

How to Reverse a Number and String in C#?

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#. 
  1. using System;  
  2.   
  3. namespace ReverseNo  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Console.WriteLine("Enter a No. to reverse");  
  10.             int Number = int.Parse(Console.ReadLine());  
  11.             int Reverse = 0;  
  12.             while(Number>0)  
  13.             {  
  14.                 int remainder = Number % 10;  
  15.                 Reverse = (Reverse * 10) + remainder;  
  16.                 Number = Number / 10;  
  17.             }  
  18.             Console.WriteLine("Reverse No. is {0}",Reverse);  
  19.             Console.ReadLine();  
  20.         }  
  21.     }  
  22. }  
Preview
 
 

Reverse a String in C#

 
The following code sample shows how to reverse a string in C#.
  1. using System;  
  2.   
  3. namespace reverseString  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             string str = "", reverse = "";  
  10.             int Length = 0;  
  11.             Console.WriteLine("Enter a Word");  
  12.             //Getting String(word) from Console  
  13.             str = Console.ReadLine();  
  14.             //Calculate length of string str  
  15.             Length = str.Length - 1;  
  16.             while(Length>=0)  
  17.             {  
  18.                 reverse = reverse + str[Length];  
  19.                 Length--;  
  20.             }  
  21.             //Displaying the reverse word  
  22.             Console.WriteLine("Reverse word is {0}",reverse);  
  23.             Console.ReadLine();  
  24.         }  
  25.     }  
  26. }  
Preview
 

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...