Write a program to Check Whether number is Prime Number using for loop in Java
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Create a Scanner object System.out.print("Enter a number:"); int num = scanner.nextInt(); boolean flag = false; for(int i = 2; i <= num/2; ++i) { // condition for nonprime number if(num % i == 0) { flag = true; break; } } if (!flag) System.out.println(num + " is a prime number."); else System.out.println(num + " is not a prime number."); } |
Output: