Objective
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.
Write Your C# Exercise
C# Exercise Example
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");
}
}
}
}
More C# Programming Exercises of Basic Data Types
Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.
In this C# exercise, you are asked to write a program that uses the conditional operator (also known as the ternary operator) to assign a boolean variable named "bothEven...
In this C# exercise, you are asked to write a program that prompts the user for a real number and displays its square root. Additionally, the program must handle any ...
This exercise in C# aims to develop a program that asks the user for three letters and displays them in reverse order. The user will input one letter at...
This exercise in C# aims to develop a program that prompts the user for a symbol and a width, and then displays a decreasing triangle of the spec...
This exercise in C# aims to develop a program that asks the user for their username and password (both as strings) and repeats the prompt as many...
This C# exercise involves creating a program that prompts the user for their username and password, both as strings. If the entered credentials do not m...