Group
C# Basic Data Types Overview
Objective
1. Continuously prompt the user to enter a decimal number.
2. Convert the decimal number to binary using successive divisions by 2.
3. Display the binary equivalent as a string of `0`s and `1`s.
4. Repeat the process until the user enters "end."
5. Ensure proper input handling to avoid errors when entering non-numeric values.
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 successive divisions.
Example C# Exercise
Show C# Code
using System;
class Program
{
static void Main()
{
string input;
while (true)
{
Console.Write("Enter a decimal number (or type 'end' to exit): ");
input = Console.ReadLine();
if (input.ToLower() == "end")
{
break;
}
if (int.TryParse(input, out int decimalNumber))
{
string binaryResult = "";
if (decimalNumber == 0)
{
binaryResult = "0";
}
else
{
while (decimalNumber > 0)
{
binaryResult = (decimalNumber % 2) + binaryResult;
decimalNumber /= 2;
}
}
Console.WriteLine($"Binary: {binaryResult}\n");
}
else
{
Console.WriteLine("Invalid input! Please enter a valid decimal number.\n");
}
}
Console.WriteLine("Program ended.");
}
}
Output
Enter a decimal number (or type 'end' to exit): 10
Binary: 1010
Enter a decimal number (or type 'end' to exit): 25
Binary: 11001
Enter a decimal number (or type 'end' to exit): 0
Binary: 0
Enter a decimal number (or type 'end' to exit): end
Program ended.