# C++ program to print the entire prime no between 1 and 300

## C++ program to print the entire prime no between 1 and 300

Here we have to write a c++ program that will print all the prime number between 1 to 300 . So what is prime number ? A number is known as prime number if it is only divisible by 1 and itself .

## C++ program to print the entire prime no between 1 and 300

The objective of the code is to print all the prime numbers between 1 to 300 .

### Algorithm:

1. Start from 1 and iterate through each number up to 300.
2. For each number, check if it is prime or not.
3. To check if a number is prime or not, divide the number by all numbers from 2 to the number/2.
4. If the number is divisible by any of the numbers in the range, it is not a prime number.
5. If the number is not divisible by any of the numbers in the range, it is a prime number.
6. Print all the prime numbers found during the iteration.

Code(C++):-

#include <iostream>
using namespace std;

int main() {
int i, j;
bool isPrime;

// Print all prime numbers between 1 and 300
for(i=1; i<=300; i++) {
isPrime = true;

// Check if the number is prime or not
for(j=2; j<=i/2; j++) {
if(i % j == 0) {
isPrime = false;
break;
}
}

// Print the number if it is prime
if(isPrime) {
cout << i << " ";
}
}

return 0;
}

Output:-

1 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 101 103 107
109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223
227 229 233 239 241 251 257 263 269 271 277 281 283 293

Explanation:

The above program starts from 1 and iterates through each number up to 300. For each number, it checks if the number is prime or not. If the number is prime, it prints the number.

The program uses two loops. The outer loop iterates from 1 to 300, while the inner loop checks if the number is prime or not. The inner loop starts from 2 and goes up to the number/2. If the number is divisible by any of the numbers in the range, it is not a prime number, and the isPrime variable is set to false. If the number is not divisible by any of the numbers in the range, it is a prime number, and the isPrime variable is set to true.

If the number is prime, the program prints the number using the cout statement. Finally, the program returns 0, indicating that the program has completed successfully.

### Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-
iMocha coding Questions:-
Tech Mahindra coding questions:-
Unthinkable Solutions coding questions:-