C# - Prime Numbers Among 2 to 30

Learn: How to find prime numbers between 2 to 20 using C#.Net program? In this article we will learn what are the prime numbers are and how to print prime numbers between 2 to 30?
[Last updated : March 19, 2023]

Firstly, understand the concept of prime numbers:

Prime Numbers

A number which is divisible by itself (or we can say number which is divisible by 1 and itself), note that: 1 is not a prime number, they are start from 2.

In this program, we are writing a program that will print only prime numbers from 2 to 30.

For example:
2 is prime number.
3 is prime number.
4 is not prime number because it can be dividing by 2.
5 is again a prime number.

C# program to find out the prime numbers among 2 to 30

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    
    class Program
    {
        static void Main(string[] args)
        {
            int i     = 0;
            int j     = 0;
            int flag  = 0;

            for (i = 2; i <= 30; i++)
            {
                j    = 2;
                flag = 0;
                while(j<=(i/2))
                {
                    if (i % j == 0)
                    {
                        flag = 1;
                        break;
                    }
                    j++;
                }

                if(flag==0)
                    Console.Write(i + " ");

            }
            Console.WriteLine();
        }
    }
}

Output

2 3 5 7 11 13 17 19 23 29

Explanation

Here, we used a loop which is running from 2 to 30 and the inner loop is running from 2 to half of the number.

If number is divisible by any number from 2 to half of the number, it will not be a prime number and loop is breaking here.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.