Objective
Write a C# program that asks the user for a number and a quantity, and displays that number repeated as many times as the user has specified. Here's an example:
Enter a number: 4
Enter a quantity: 5
44444
You must display it three times: first using "while", then "do-while" and finally "for".
Write Your C# Exercise
C# Exercise Example
using System; // Importing the System namespace to use Console functionalities
class Program
{
// Main method where the program execution begins
static void Main()
{
// Asking the user to enter a number
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine()); // Reading the number entered by the user
// Asking the user to enter the quantity of repetitions
Console.Write("Enter a quantity: ");
int quantity = int.Parse(Console.ReadLine()); // Reading the quantity entered by the user
// First: Using a "while" loop to display the number the specified quantity of times
Console.WriteLine("Using while loop:");
int count = 0; // Initializing a counter variable
while (count < quantity) // Loop continues as long as count is less than the quantity
{
Console.Write(number); // Displaying the number
count++; // Incrementing the counter
}
Console.WriteLine(); // Moving to a new line after the repetition
// Second: Using a "do-while" loop to display the number the specified quantity of times
Console.WriteLine("Using do-while loop:");
count = 0; // Re-initializing the counter variable
do
{
Console.Write(number); // Displaying the number
count++; // Incrementing the counter
} while (count < quantity); // Loop continues as long as count is less than the quantity
Console.WriteLine(); // Moving to a new line after the repetition
// Third: Using a "for" loop to display the number the specified quantity of times
Console.WriteLine("Using for loop:");
for (int i = 0; i < quantity; i++) // Looping from 0 to quantity-1
{
Console.Write(number); // Displaying the number
}
Console.WriteLine(); // Moving to a new line after the repetition
}
}