Java Online Compiler
Example: Prime Number Check using For Loop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Prime Number Check using For Loop import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter a number System.out.print("Enter a number: "); int number = scanner.nextInt(); // Step 3: Initialize a boolean flag to track primality boolean isPrime = true; // Step 4: Handle special cases for numbers less than or equal to 1 if (number <= 1) { isPrime = false; } else { // Step 5: Loop from 2 up to number - 1 for (int i = 2; i < number; i++) { // Step 6: Check if the number is divisible by 'i' if (number % i == 0) { isPrime = false; // If divisible, it's not prime break; // No need to check further } } } // Step 7: Print the result based on the isPrime flag if (isPrime) { System.out.println(number + " is a prime number."); } else { System.out.println(number + " is not a prime number."); } // Step 8: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS