Adsense 728 * 15

Search

Custom Search

Print Prime Numbers Between 1 to 100 in C, C++

Write a C, C++ program to print prime numbers between 1 to 100. In this tutorial, we are going to write a C, C++ code to print prime numbers between 1 to 100.


What is a Prime number?



A prime number is a number that is greater than 1, and there are only two whole-number factors 1 and itself.

Example of prime numbers are -  2, 3, 5, 7, 11, 13, 17, 19, 23 etc.

C Program to Check whether a Number is Prime or not

C, C++ Program to Check whether a Number is prime or not

Sorting algorithms and their time complexity


C Program to Print Prime Numbers Between 1 to 100


Let's write a c code to print prime numbers between 1 to 100.

#include<stdio.h>

int main() {

   int i=2, j, p;
 
   while(i <= 100){
 
     /* Initially P is 1. */
   
      p = 1;

      for(j = 2; j < i; j++){
   
       /* Check if it is divisible by any other number,
          other than 1 or itself. */
       
         if(i % j == 0) {        
            p = 0;
         }      
    }
    
    if(p) {
     printf("%d ",i);
    }
    
    i++; 
  }
 
 return 0;
}
    


Output :


2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

C++ Program to Print Prime Numbers Between 1 to 100

#include<iostream>

using namespace std;

int main()
{

 int i = 2, j, p;
 
 while(i <= 100){
 
   /* Initialize P */
   
    p = 1;

    for(j = 2; j < i; j++){
   
    /*if it is divisible by any other number,
      other than 1 or itself then it's not a prime
      number. */
       
       if(i % j == 0){
        
            /* If it's not a prime, Set p=0 . */
            p = 0;
       }
      
    }
    
    /* Print prime number. */
    
    if(p) {
      cout << i << " ";
    }
    
    i++; 
 }
 
 return 0;
}

This program illustrated, how to print prime numbers between 1 to 100. There is also a better way to print prime numbers between 1 to n using sieve algorithm.

Alternatively, Take the value of n as an input from a user and use the same logic which we used while printing prime numbers between 1 to 100.

Program to print 1 to 100 numbers using loop

Programming questions on Arrays




No comments:

Post a Comment