COME 2 CODE
Learn by Yourself

Program to Print all Prime Numbers up to a given Number

Hello friends, in this tutorial we are going to write a program to find all the prime numbers upto a given number. So, open your IDE and make a new Project. Now, write the following code in Main.java file.

Main.java :

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    int num;

    System.out.println("Enter the number : ");
    Scanner scanner = new Scanner(System.in);
    num = scanner.nextInt();

    System.out.println("The prime numbers are : ");
    for (int i = 2; i <= num; i++) {
      if (primeNumber(i)) {
        System.out.println(i);
      }
    }
  };
    public static boolean primeNumber(int n) {
      for (int i = 2; i < n; i++) {
        if ((n % i) == 0) {
          return false;
        }
      }
      return true;
  }
}

Your output will be like this.

Output :

C:/Users/Username/Desktop>Enter the number :
15
The prime numbers are :
2
3
5
7
11
13
QUICK LINKS :