Dremendo Tag Line

Input number and check prime or not using for loop in Java

for Loop - Question 10

In this question, we will see how to input a number and check if it is a prime number or not in Java programming using for loop. To know more about for loop click on the for loop lesson.

Q10) Write a program in Java to input a number and check if it is a prime number or not using for loop.

Program

import java.util.Scanner;

public class Q10
{
    public static void main(String args[])
    {
        int i,n,fc=0;
        Scanner sc=new Scanner(System.in);

        System.out.print("Enter a number ");
        n=sc.nextInt();
        for(i=1; i<=n; i=i+1)
        {
            if(n%i==0)
            {
                fc=fc+1;		// counting the factors of the given number
            }
        }

        if(fc==2)		// a prime number has only two factors
        {
            System.out.print("Prime Number");
        }
        else
        {
            System.out.print("Not Prime Number");
        }
    }
}

Output

Enter a number 17
Prime Number
video-poster