![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements