Ejercicio
Binario
Objetivo
Cree un programa en C# que solicite al usuario un número decimal y muestre su equivalente en forma binaria. Debe repetirse hasta que el usuario ingrese la palabra "fin". No debe usar "ToString", sino divisiones sucesivas.
Código de Ejemplo
using System; // Import the System namespace for basic functionality
class Program // Define the main class
{
static void Main() // The entry point of the program
{
// Infinite loop to keep asking the user for input until they enter "end"
while (true)
{
// Ask the user for a number or the word "end" to quit
Console.Write("Enter a decimal number (or 'end' to quit): ");
string input = Console.ReadLine(); // Read the input as a string
// If the user enters "end", exit the loop and end the program
if (input.ToLower() == "end")
{
Console.WriteLine("Goodbye!");
break; // Exit the loop
}
// Try to parse the input as an integer
if (int.TryParse(input, out int number))
{
// Start with an empty string for the binary representation
string binary = "";
// Perform successive divisions by 2 to get the binary digits
while (number > 0)
{
// Get the remainder when dividing by 2 (this will be either 0 or 1)
int remainder = number % 2;
binary = remainder + binary; // Add the remainder to the binary string
number = number / 2; // Divide the number by 2
}
// If the number is 0, the binary representation should be "0"
if (string.IsNullOrEmpty(binary))
{
binary = "0";
}
// Display the binary result
Console.WriteLine($"Binary: {binary}\n");
}
else
{
Console.WriteLine("Please enter a valid number.\n");
}
}
}
}