Ejercicio
Muchas divisiones
Objetivo
Escriba un programa en C# para pedir al usuario dos números y mostrar su división y el resto de la división. Avisará si se introduce 0 como segundo número, y finalizará si se introduce 0 como primer número:
¿Primer número? 10
¿Segundo número? 2 División es 5
El resto es 0
¿Primer número? 10
¿Segundo número? 0
No se puede dividir por 0
¿Primer número? 10
¿Segundo número? 3
La división es 3
El resto es 1
¿Primer número? 0
¡Adiós!
Código de Ejemplo
using System; // Importing the System namespace to use Console functionalities
class Program
{
// Main method where the program execution begins
static void Main()
{
int firstNumber, secondNumber; // Declaring variables to store the two numbers
// Asking the user to input the first number
Console.Write("First number? ");
firstNumber = int.Parse(Console.ReadLine()); // Reading the first number
// If the first number is 0, the program ends with a message
if (firstNumber == 0)
{
Console.WriteLine("Bye!"); // Displaying "Bye!" if the first number is 0
return; // Exiting the program
}
// Asking the user to input the second number
Console.Write("Second number? ");
secondNumber = int.Parse(Console.ReadLine()); // Reading the second number
// If the second number is 0, show an error message and end the program
if (secondNumber == 0)
{
Console.WriteLine("Cannot divide by 0"); // Informing the user that division by zero is not allowed
return; // Exiting the program
}
// If the second number is not 0, perform the division and display the result
int division = firstNumber / secondNumber; // Performing integer division
int remainder = firstNumber % secondNumber; // Calculating the remainder
// Displaying the results
Console.WriteLine($"Division is {division}"); // Showing the division result
Console.WriteLine($"Remainder is {remainder}"); // Showing the remainder result
}
}