Objective
Write a C# program to ask the user for a real number and display its square root. Errors must be trapped using "try..catch".
Does it behave as you expected?
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
{
try
{
// Ask the user to enter a real number
Console.Write("Enter a real number: ");
double number = Convert.ToDouble(Console.ReadLine()); // Convert the input to a double
// Check if the number is negative before attempting to calculate the square root
if (number < 0)
{
// If the number is negative, throw an exception as we can't calculate the square root of a negative number
throw new InvalidOperationException("Cannot calculate the square root of a negative number.");
}
// Calculate and display the square root of the number
double squareRoot = Math.Sqrt(number);
Console.WriteLine($"The square root of {number} is {squareRoot}");
}
catch (FormatException)
{
// Catch the FormatException if the user doesn't input a valid number
Console.WriteLine("Error: Please enter a valid real number.");
}
catch (InvalidOperationException ex)
{
// Catch the InvalidOperationException if the number is negative
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
// Catch any other unexpected exceptions
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}
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#.
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...
This C# programming exercise requires creating a program that asks the user for two numbers and an operation to perform on them. The supported operations are ...
In this C# programming exercise, you need to create a program that asks the user for two numbers and a mathematical operation to perform between them. Supporte...