Write a program that reverses the input number n. Formulate an equation to come up with the answer:
(Apply the three loop statements in your solutions) Sample input/output dialogue:
Enter a number: 1238 Input data
Reverse number: 8321 Output value
1st Solution using- for loop
using System;
using System.Collections.Generic;
namespace App
{
class Program
{
public static void Main()
{
Console.Write("Enter a number: ");
string number = Console.ReadLine();
Console.WriteLine("Reverse number (using - for loop): {0}", ReverseWithFor(number));
Console.WriteLine("Reverse number (using - while loop): {0}", ReverseWithWhile(number));
Console.WriteLine("Reverse number (using - do while loop): {0}", ReverseWithDoWhile(number));
Console.ReadLine();
}
private static string ReverseWithFor(string text)
{
string reverseString = "";
for (int i = text.Length - 1; i >= 0; i--)
{
reverseString += (text[i]);
}
return reverseString;
}
private static string ReverseWithWhile(string text)
{
string reverseString = "";
int i = text.Length - 1;
while (i >= 0)
{
reverseString += (text[i]);
i--;
}
return reverseString;
}
private static string ReverseWithDoWhile(string text)
{
string reverseString = "";
int i = text.Length - 1;
do
{
reverseString += (text[i]);
} while (--i >= 0);
return reverseString;
}
}
}
Comments
Leave a comment