Program to find all prime numbers in given range

Description

To find all prime numbers in a given range, take a loop and check if number
is prime or not. If it is prime print it else skip it.

C/C++

/* C Program to find all prime numbers in given range */
//Save it as PrimeNumbersInGivenRange.c

#include<stdio.h>
#include<stdbool.h>
bool checkPrime(int);

int main(){

    int i, range;

    printf("Enter a range : ");
    scanf("%d",&range);

    printf("The all prime numbers are : ");
    for(i=2;i<=range;i++) {
        if(checkPrime(i)) {
            printf("\n%d",i);
        }
    }
}

//Function to check prime number
bool checkPrime(int num) {

    int k, flag = 0;
    for(k=2;k<=num/2;k++) {
        if(num%k == 0 ) {
            flag = 1;
            break;
        }
    }

    if(flag == 1)
        return false;
    else
        return true;
}
Input:
Enter a range : 10

Output:
The all prime numbers are : 
2
3
5
7

Java

/* Java Program to find all prime numbers in given range */
//Save it as PrimeNumbersInGivenRange.java

import java.io.*;
import java.util.Scanner;

public class PrimeNumbersInGivenRange {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter a range : ");
        int range = scanner.nextInt();
        
        System.out.println("The all prime numbers are : ");
        for(int i=2;i<=range;i++) {
            if(checkPrime(i)) {
                System.out.println(i);
            }
        }
    }
    
    //Function to check prime number
    private static boolean checkPrime(int num) {

        int flag = 0;
        for(int k=2;k<=num/2;k++) {
            if(num%k == 0 ) {
                flag = 1;
                break;
            }
        }
        
        if(flag == 1)
            return false;
        else
            return true;
    }
}
Input:
Enter a range : 
10

Output:
The all prime numbers are : 
2
3
5
7

Related programs

1) Program to Check Whether a Number is Prime or Not
2) Program to Check Whether a Number is Even or Odd
3) Check whether a given number is a perfect number or not
4) Program to find the average of numbers in a given range
5) Program to generate Random number in a given Range
6) Program to print all Squares of numbers from 1 to given Range
7) Program to calculate Gross Salary
8) Program to calculate percentage mark of student
9) Program to reverse a number
10) Program to display multiplication table of a number
Share Me

Leave a Reply