Prime Number Program in C#

In this post, we will learn about Prime Number Program in C# with an example.

Description:

In my previous posts I have explained various topics likeĀ Fibonacci Series in C#, Multi Dimensional array in C#, Arrays In C#, Fill DropDownList from JSON Array using jQuery, Anonymous Types In C# ,Sealed Class in C#, Continue keyword in C#.Net, Difference between string and StringBuilder in C#, Difference between a struct and a class in C#.

Now in this post, I will explain Prime Number Program in C#.Net with appropriate example. A prime number is a number which is greater than 1 and divided by 1 or itself. In other words, prime numbers cannot be divided by other numbers than itself or 1.

For example 2, 3, 5, 7, 11, 13, 17, 19, 23,29,31…. are the prime numbers.



Now create Console Application in Visual Studio and write below lines of code in it.

using System;
using System.Collections;
using System.Collections.Generic;

namespace DotNetK
{
    class Program
    {
        static void Main(string[] args)
        {
            // Program to check whether the given number is prime or not

            int number, k, m = 0, flag = 0;
            Console.Write("Enter the Number to check Prime: ");
            number = int.Parse(Console.ReadLine());
            m = number / 2;
            for (k = 2; k <= m; k++)
            {
                if (number % k == 0)
                {
                    Console.Write("Number is not Prime.");
                    flag = 1;
                    break;
                }
            }
            if (flag == 0)
            Console.Write("Number is Prime.");  

            Console.ReadKey(); // To retain the screen
        }
    }    
}




Read :

Summary

You can also read about ASP.NET,C#.NET, JQUERY, AJAX.
I hope you get an idea about Prime Number Program in C#.
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website