Google Add

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




4 comments:

  1. how can i check if a number from the user is between 1 and 100 inclusive.

    ReplyDelete
    Replies
    1. Simple way is to ask to user for entering minimum limit and maximum limit of number between which prime numbers need to be printed.

      Delete
  2. I need a c++ program to print all non-prime numbers less than 100 and to check whether each of these numbers is a perfect square.

    ReplyDelete
    Replies
    1. 1.In the above post instead of
      if(p) {
      cout << i << " ";
      }
      simply change it to
      if(!p) {
      cout << i << " ";
      }
      and you will get non-prime numbers.

      2.http://www.cprogrammingcode.com/2016/04/program-to-check-perfect-square-in-c-c.html

      Delete