C# Program to check if a number is prime or not


To calculate whether a number is prime or not, we have used a for loop. Within that on every iteration, we use an if statement to find that the remainder is equal to 0, between the number itself.

for (int i = 1; i <= n; i++) {
   if (n % i == 0) {
      a++;
   }
}

A counter a is also added, which increments only twice if the number is prime i.e. with 1 and the number itself. Therefore, if the value of a is 2, that would mean the number is prime. 

Example

Let us see the complete example to check if a number is prime or not

Live Demo

using System;
namespace Demo {
   class MyApplication {
      public static void Main() {
         int n = 5, a = 0;
         for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
               a++;
            }
         }
         if (a == 2) {
            Console.WriteLine("{0} is a Prime Number", n);
         } else {
            Console.WriteLine("Not a Prime Number");
         }
         Console.ReadLine();
      }
   }
}

Output

5 is a Prime Number

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 10-Sep-2023

36K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements