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.

What is 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.

Program to Check whether Number is Prime.

Search Algorithm (Linear and Binary Search).


C Program 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. If you want to print Prime Numbers between 1 to n, take n as a input from user and use the same logic which we used while printing prime number between 1 to 100.

No comments:

Post a Comment