Header Ads Widget

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 <stdio.h>

// Function to check if a number is prime or not
int is_prime(int n) {
if (n <= 1) {
return 0;
}
for (int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}

int main() {
// Print all prime numbers between 1 and 300
for (int i = 1; i <= 300; i++) {
if (is_prime(i)) {
printf("%d ", 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 by calling the is_prime function. If the number is prime, it prints the number.

The is_prime function takes a number as input and checks if it is prime or not. If the number is less than or equal to 1, it is not prime. Otherwise, the function iterates through all numbers from 2 to the number/2 and checks if the number is divisible by any of them. If the number is divisible by any of the numbers in the range, it is not a prime number, and the function returns 0. If the number is not divisible by any of the numbers in the range, it is a prime number, and the function returns 1.

If the number is prime, the program prints the number using the printf statement. Finally, the program terminates.

Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-


Post a Comment

0 Comments