Objective
Write a C# program that asks the user for an integer and determines if it is a prime number or not.
Write Your C# Exercise
C# Exercise Example
using System; // Import the System namespace, which contains fundamental classes like Console
class Program // Define the Program class
{
static void Main() // The entry point of the program
{
// Ask the user to enter an integer
Console.Write("Enter an integer: ");
int number = int.Parse(Console.ReadLine()); // Read and convert the user input to an integer
// Check if the number is less than 2, as prime numbers are greater than 1
if (number < 2)
{
Console.WriteLine("The number is not prime."); // If the number is less than 2, it's not prime
}
else
{
bool isPrime = true; // Assume the number is prime unless proven otherwise
// Check divisibility from 2 to the square root of the number
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (number % i == 0) // If the number is divisible by i, it's not prime
{
isPrime = false; // Set isPrime to false if a divisor is found
break; // Exit the loop as we've found a divisor
}
}
// Display whether the number is prime or not
if (isPrime)
{
Console.WriteLine("The number is prime."); // If no divisors were found, it's prime
}
else
{
Console.WriteLine("The number is not prime."); // If a divisor was found, it's not prime
}
}
}
}
More C# Programming Exercises of Flow Control
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 calculates the change for a purchase, using the largest possible coins or bills. The program s...
This exercise in C# aims to develop a program that asks the user for two numbers and displays their division. The program should handle potential errors...
In this C# exercise, you will learn how to create a program that determines whether a number entered by the user is positive or negative. The program will prom...
In this C# exercise, you will learn how to create a program that asks the user for a number. If the entered number is not zero, the program will ask for a second number and ...
In this C# exercise, you will learn how to create a program that asks the user for two numbers. If the second number is not zero, the program will perform the division...
In this C# exercise, you will learn how to modify the previous program using the else control structure. The program will ask the user for two numbers, and if the sec...