Exercise
Hexadecimal and binary
Objetive
Write a C# program to ask the user for a number an display it both in hexadecimal and binary. It must repeat until the user enters 0.
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 0
while (true)
{
// Ask the user for a number
Console.Write("Enter a number (0 to quit): ");
int number = int.Parse(Console.ReadLine()); // Read the input and convert it to an integer
// If the number is 0, exit the loop and end the program
if (number == 0)
{
Console.WriteLine("Goodbye!");
break; // Exit the loop
}
// Display the number in hexadecimal
Console.WriteLine($"Hexadecimal: {number:X}");
// Display the number in binary
Console.WriteLine($"Binary: {Convert.ToString(number, 2)}\n");
}
}
}