Home » .Net

C# program to find out the 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?

Firstly, understand the concept of 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.

Consider the program:

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

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.