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 tosqrt(num)(expressed asi * i <= numto avoid needingmath.h) — if any divisor is found,is_primeis set to 0 and the inner loop exits early viabreak. - Numbers that survive the inner loop untouched are prime and get printed, incrementing
count. - Once 10 primes have been printed, the outer loop's
breakstops the search immediately, even ifnumhasn't reachednyet.
Sample Output
Enter upper limit n: 50
2 3 5 7 11 13 17 19 23 29