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
2nd Solution using- while loop
3rd Solution using- do while loop
class Program
{
public static void Main()
{
Console.Write("Enter a number: ");
string input = Console.ReadLine();
string output = ReverseWithDoWhile(input);
Console.WriteLine($"Reverse number: {output}");
Console.ReadLine();
}
public static string ReverseWithFor(string text)
{
StringBuilder output = new StringBuilder(text.Length);
for (int i = text.Length - 1; i >= 0; i--)
output.Append(text[i]);
return output.ToString(); ;
}
public static string ReverseWithWhile(string text)
{
StringBuilder output = new StringBuilder(text.Length);
int i = text.Length - 1;
while (i >= 0)
{
output.Append(text[i]);
i--;
}
return output.ToString(); ;
}
public static string ReverseWithDoWhile(string text)
{
StringBuilder output = new StringBuilder(text.Length);
int i = text.Length - 1;
do
{
output.Append(text[i]);
} while (--i >= 0);
return output.ToString(); ;
}
}
Comments
Leave a comment