Exercise
Binary
Objetive
Write a C# program that asks the user for a decimal number and displays its equivalent in binary form. It should be repeated until the user enters the word "end." You must not use "ToString", but succesive divisions.
Example Code
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");
}
}
}
}