Q:

Write C# program to check whether a number is Prime number or not using while & for loop

0

Write C# program to check whether a number is Prime number or not using while & for loop

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.

 

Check whether a number is Prime number or not using while loop
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
public class csharpExercise
{
    static void Main(string[] args)
    {
        int num, i, f;
 
       /*Reading number      
        */
 
        Console.Write("Enter any number: ");
        num = Convert.ToInt32(Console.ReadLine());
 
        f = 0;
        i = 2;
        while (i <= num / 2)
        {
            if (num % i == 0)
            {
                f = 1;
                break;
            }
            i++;
        }
        if (f == 0)
           Console.WriteLine(num+" is a Prime Number");
        else
            Console.WriteLine(num + " is not a Prime Number");
 
 
        Console.ReadLine();
    }
}
Check whether a number is Prime number or not for while loop
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
public class csharpExercise
{
    static void Main(string[] args)
    {
        int num, i, f;
 
        /*Reading number      
        */
 
        Console.Write("Enter any number: ");
        num = Convert.ToInt32(Console.ReadLine());
 
        f = 0;
        for (i = 2; i <= num / 2; i++)
        {
            if (num % i == 0)
            {
                f = 1;
                break;
            }
        }
        if (f == 0)
            Console.WriteLine(num+ " is a Prime Number");
        else
            Console.WriteLine(num+" is a Not Prime Number");        
 
        Console.ReadLine();
    }
}

Result:

Enter any number: 19

19 is a Prime Number

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Write C# program to check whether a number is pali... >>
<< Write C# program to calculate compound Interest...