In this post we will create a simple example of an algorithm. We will create a program to reverse the Digits of a Number that entered by user in C# console Application.
Output:
Solution 1: Convert integer to array firstly, then reverse the array and convert array to back integer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Program { static void Main(string[] args) { int num1, num2; Console.Write("Enter your number :"); num1 = Convert.ToInt32(Console.ReadLine()); char[] arr = num1.ToString().ToCharArray(); Array.Reverse(arr); num2 = Convert.ToInt32(new String(arr)); Console.WriteLine("Reversed number :{0}",num2); Console.ReadLine(); } } |
Solution 2: As a better algorithm technique, use a loop to reverse a number sequence
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Program { static void Main(string[] args) { int num1, num2; string seq=""; Console.Write("Enter your number :"); num1 = Convert.ToInt32(Console.ReadLine()); while (true) { seq += (num1 % 10).ToString(); num1 = num1 / 10; if (num1 <= 0) break; } num2 = Convert.ToInt32(seq); Console.WriteLine("Reversed number :"+num2); Console.ReadLine(); } } |
You can find more similar examples of programming for this programming language in the site.