Java Program to Print All Prime Numbers from 1 to N

by | Jan 7, 2023 | Java, Java Programs

Introduction

This program passes an integer number as input to the code. The objective is to print all prime numbers from 1 to that number ‘N’.

Example

Input: N = 10
Output: 2, 3, 5, 7

Input: N = 5
Output: 2, 3, 5

Approach to the Problem

  • As a first step, the input number ‘N’ is passed on to the program.
  • Then a loop is introduced into the program. The purpose of this loop is to traverse through all numbers starting from 1 up to that number.
  • While the loop control variable (LCV) takes values from 1 to N at every iteration, the LCV is then tested for each number to check whether the given number is a prime number or not.

Sample Code

class Demo
{
static void print_primes_till_N(int N)
int i, j, flag;
System.out.println (“Sorted Prime numbers between 1 and ” + N + “are :”);
for (int i = 1; i< = N; i++)
{
if (i=1 || i=0)
continue;
flag = 1;
for (j = 2; j < = i/2; ++j)
{
if (i%j == 0)
{
flag = 0;
break;
}
}
//if the value of the flag is 1, then the number is a prime number
// similarly, if the flag is 0, this means that the LCV ‘i’ is not prime.
if (flag == 1)
System.out.println (i + “;”);
}
}
public static void main (String args [])
{
int N = 30;
print_primes_till_N(N);
}
}

 

OUTPUT

Sorted Prime numbers between 1 and 30  2; 3; 5; 7; 11; 13; 17; 19; 23; 29.

 

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.