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++.


while(Condition){
   //Statement
     Increment/Decrement  
}

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

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

#include<iostream>
using namespace std;

int main() {

    int upto, i, j, p;

    cout << "Enter a number:";
    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 << i <<endl;
        }
    }

    return 0;
}

Output:

Enter a number:50
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47