Computer Applications
Write a program in Java to accept a number. Check and print whether it is a prime number or not.
A prime number is a number which is divisible by 1 and itself only. For example 2, 3, 5, 7, 11, 13 are all prime numbers.
Java
Java Iterative Stmts
140 Likes
Answer
import java.util.Scanner;
public class KboatPrimeCheck
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int n = in.nextInt();
int c = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
c++;
}
}
if (c == 2) {
System.out.println(n + " is a prime number");
}
else {
System.out.println(n + " is not a prime number");
}
}
}
Output
Answered By
59 Likes