C++ Program to print all prime numbers between 1 to n


In this program, You will learn how to print all prime numbers between 1 to n in C++.


Some list of prime numbers is 2, 3, 5, 7, 11, 13


Example: How to print all prime numbers between 1 to n in C++

Run it Now
#include<iostream>
using namespace std;

int main() {

    int upto, i, j, p;

    cout << "Enter upto Prime Numbers :";
    cin>>upto;

    for (i = 2; i <= upto; i++) {
        p = 1;
        j = 2;
        while (j < i) {
            if (i % j == 0) {
                p = 0;
                break;
            }
            j++;
        }
        if (p == 1) {
            cout << "\n" << i;
        }
    }

    return 0;
}

Output:

Enter upto Prime Numbers :10
2
3
5
7