c-sharp
  1. c-sharp-program-to-check-whether-a-number-is-prime-or-not

Program to Check Whether a Number is Prime or Not - (C# Basic Programs)

Checking whether a number is prime or not is a common programming exercise that helps improve coding skills. In this tutorial, we will discuss a program using C# language to check whether a given number is a prime number or not.

Syntax

The syntax for checking whether a number is prime or not in C# programming language is as follows:

static bool IsPrime(int number)
{
    if (number <= 1)
        return false;
        
    for(int i = 2; i <= Math.Sqrt(number); i++)
    {
        if(number % i == 0)
            return false;
    }
    return true;
}

Example

using System;

class Program
{
    static bool IsPrime(int number)
    {
        if (number <= 1)
            return false;

        for (int i = 2; i <= Math.Sqrt(number); i++)
        {
            if (number % i == 0)
                return false;
        }

        return true;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Enter a number: ");
        int number = Convert.ToInt32(Console.ReadLine());

        if (IsPrime(number))
            Console.WriteLine(number + " is a prime number.");
        else
            Console.WriteLine(number + " is not a prime number.");
    }
}

Output:

Enter a number: 17
17 is a prime number.

Explanation

The IsPrime method in the C# program first checks whether the number is less than or equal to 1. If yes, it returns false as any number less than or equal to 1 is not considered prime.

Otherwise, it loops through all the numbers starting from 2 up until the square root of the given number and checks whether the number is divisible by any of the numbers, starting from 2. If it is, then the number is not considered prime and the method returns false. If none of the numbers divide the given number, the number is considered prime and the method returns true.

In the Main method, we use the IsPrime method to check whether a user-given number is prime or not, and output the result to the console.

Use

Checking whether a given number is prime or not is a popular programming problem that helps improve coding skills, particularly with loops and conditional statements, and logical problem solving.

Summary

In this tutorial, we discussed a C# program to check whether a given number is a prime number or not. We explained the syntax, example, explanation, and use of the program. By practicing with this program, programmers can learn more about loops, conditional statements, and logical problem solving.

Published on: