C++ Program to Print First n Prime Numbers using For Loop

Write C++ Program to Print First n Prime Numbers using For Loop

// CPP Program to Print First n Prime Numbers using For Loop

#include <iostream>
#include <stdbool.h>

using namespace std;

bool isPrime(int n)
{
	if(n == 1 || n ==0)
		return false;

	int i;
	for(i = 2; i < n; i++)
	{
		if(n % i == 0)
		{
			return false;
		}
	}

	return true;
}

int main()
{
	int n;

	cout << "Enter the number :--> ";
	cin >> n;

	int i = 1 ;
	cout << "First " << n << " Prime Numbers are :--> ";

        int Count = 0;
        i = 2;
	for(; Count < n; )
	{
		if(isPrime(i))
		{
			cout << i << " ";
			Count++;
		}
		i++;
	}
	return 0;
}

Output:

Enter the number :--> 7
First 7 Prime Numbers are :--> 2 3 5 7 11 13 17

≪ Previous | Next ≫