Ejercicio
Número Repetido
Objectivo
Escribe un programa en C# que pida un número y una cantidad, y muestre ese número repetido tantas veces como el usuario haya indicado, como en el siguiente ejemplo:
Introduzca un número: 4
Introduzca un importe: 5
44444
Debe mostrarlo tres veces: primero usando "while", luego "do-while" y finalmente "for".
Ejemplo Ejercicio C#
Mostrar Código C#
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
}
}
Salida
Enter a number: 5
Enter a quantity: 3
Using while loop:
555
Using do-while loop:
555
Using for loop:
555
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp