In this article, we will learn how to write a C program to **print prime numbers** **from 1 to 100**. We will also see a program to display prime numbers from 1 to n where value of n is entered by user.

## Program to print Prime Numbers from 1 to 100

In this program, we have a user defined function `checkPrimeNum()`

, this function checks whether the number is prime or not.

We are running a loop from 1 to 100, inside this loop we are calling `checkPrimeNum()`

to check every number between 1 and 100. If this function returns 1 we are displaying the number else we are ignoring it, thus printing only prime numbers from 1 to 100.

#include <stdio.h> int checkPrimeNum(int num) { // Any number less than 2 is not a prime number if(num < 2){ return 0; } //if greater than 2 then check for prime number else{ int temp = num/2; for(int i = 2; i <=temp; i++) { if(num % i == 0) { //return 0 if number is not prime return 0; } } } // return 1 if number is prime return 1; } int main() { // change this number as per the requirement. Here, we are printing // the prime numbers from 1 to 100 so the n is 100. If you // want to display first 50 prime numbers then change it to 50 int n = 100; printf("Prime numbers from 1 to %d: ", n); for(int i=1; i <= n; i++){ if(checkPrimeNum(i)) printf("%d ",i); } return 0; }

**Output:**

## Program to print Prime Numbers from 1 to N

The logic used in this program is similar to the first program. Here, we are displaying prime numbers from 1 to n, the value of n is entered by user. This value is captured using scanf() and a loop runs from 1 to n to print first n prime numbers.

#include <stdio.h> int checkPrimeNum(int num) { // Any number less than 2 is not a prime number if(num < 2){ return 0; } //if greater than 2 then check for prime number else{ int temp = num/2; for(int i = 2; i <=temp; i++) { if(num % i == 0) { //return 0 if number is not prime return 0; } } } // return 1 if number is prime return 1; } int main() { int n; //taking the value of n from user printf("Enter the value of n: "); scanf("%d", &n); printf("First %d prime numbers: ", n); for(int i=1; i <= n; i++){ if(checkPrimeNum(i)) printf("%d ",i); } return 0; }

**Output:**

Enter the value of n: 10 First 10 prime numbers: 2 3 5 7

Practice same program in Java.