Ques:-19) Write a program to print all prime numbers from 1 to 300. (Hint:  Use nested loops, break and continue).

Below is a C program to print all prime numbers between 1 and 300 using nested loops, along with break and continue statements:

				
					#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
printf("Prime nom btw 1 to 300 are:\n");
for(i=1;i<=300;i++)
{
for(j=2;j<=i;j++)
{
if(i%j==0)
{
break;
}
}
if(j==i)
printf("%d",i);
}
getch();
}

				
			

Out Put

				
					prime number between 1 to 300

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.
				
			

Another Example

				
					#include <stdio.h>

int main() {
    int num, i;
    int isPrime;

    printf("Prime numbers between 1 and 300 are:\n");

    for (num = 2; num <= 300; num++) {
        isPrime = 1;  // Assume the number is prime

        for (i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = 0;  // num is not a prime number
                break;  // No need to check further, exit the loop
            }
        }

        if (isPrime) {
            printf("%d ", num);  // Print the prime number
        }
    }

    printf("\n");
    return 0;
}

				
			

Explanation:

  1. Initialization:

    • The outer for loop iterates through numbers from 2 to 300.
    • isPrime is used as a flag to determine if the current number is prime.
  2. Checking Primality:

    • The inner for loop checks if num is divisible by any number from 2 to num / 2. If it finds any divisor, it sets isPrime to 0 and breaks out of the loop.
  3. Printing Prime Numbers:

    • If isPrime remains 1 after the inner loop, it means the number is prime, and it is printed.
  4. Output:

    • The program will print all prime numbers between 1 and 300.

Sample Output:

				
					Prime numbers between 1 and 300 are:
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

				
			

Compile and run this program using a C compiler to see the prime numbers between 1 and 300 printed on the screen.

Scroll to Top