Prime Number using C++ Programming


This program generates and prints prime numbers between 1 and 100. Here's how it works:

  • Declare two integer variables n and c and initialize c to 0.
  • Use a for loop to iterate through each integer n between 1 and 100 (inclusive).
  • For each value of n, use another for loop to iterate through each integer i between 1 and n (inclusive).
  • For each value of i, check if n is divisible by i. If it is, increment c by 1.
  • After the inner loop completes, check if c is equal to 2. If it is, n is prime, so print it to the console.
  • Reset c to 0 and continue with the outer loop until all values of n between 1 and 100 have been checked.

Note that the program is using the fact that a number is prime if it has exactly two divisors, namely 1 and itself.

Source Code

//Program for prime number between 1-100
#include<iostream>
using namespace std;
int main()
{
    int n,c=0;
    for(n=1; n<=100; n++)
    {
 
        for(int i=1; i<=n; i++)
        {
            if(n%i==0)
                c++;
        }
        if(c==2)
        {
            cout<<n<<endl;
        }
        c=0;
    }
    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
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples