Print the First N Prime Numbers Using a For Loop and Break in C

This program prints prime numbers between 1 and n, stopping once 10 prime numbers have been printed, using a for loop and a break statement.

C Program

#include <stdio.h>

int main() {
    int n, num, i, count = 0, is_prime;

    printf("Enter upper limit n: ");
    scanf("%d", &n);

    for (num = 2; num <= n; num++) {
        is_prime = 1;

        for (i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                is_prime = 0;
                break;
            }
        }

        if (is_prime) {
            printf("%d ", num);
            count++;
        }

        if (count == 10) {
            break;
        }
    }

    printf("\n");

    return 0;
}

Explanation

  • For each candidate num, the inner loop tests divisibility only up to sqrt(num) (expressed as i * i <= num to avoid needing math.h) — if any divisor is found, is_prime is set to 0 and the inner loop exits early via break.
  • Numbers that survive the inner loop untouched are prime and get printed, incrementing count.
  • Once 10 primes have been printed, the outer loop's break stops the search immediately, even if num hasn't reached n yet.

Sample Output

Enter upper limit n: 50
2 3 5 7 11 13 17 19 23 29

Leave a Comment