🚀Beginner

Print Prime Numbers From 1 to N

Display all primes up to N

This program prints all prime numbers from 1 to N, where N is entered by the user. A prime number is a number greater than 1 that has no divisors other than 1 and itself.

📝 Example

Input: N = 20

Output:

2 3 5 7 11 13 17 19

📋 Algorithm

  1. Take N as input from the user
  2. Loop through numbers from 2 to N
  3. For each number, check if it's prime
  4. If prime, print the number

C Program to Print Prime Numbers from 1 to N

prime_1_to_n.c
C
1#include <stdio.h>
2#include <stdbool.h>
3
4// Function to check if a number is prime
5bool isPrime(int num) {
6 if (num <= 1) return false;
7 if (num == 2) return true;
8 if (num % 2 == 0) return false;
9
10 // Check odd numbers up to sqrt(num)
11 for (int i = 3; i * i <= num; i += 2) {
12 if (num % i == 0)
13 return false;
14 }
15 return true;
16}
17
18int main() {
19 int n;
20
21 printf("Enter N: ");
22 scanf("%d", &n);
23
24 printf("Prime numbers from 1 to %d:\n", n);
25
26 for (int i = 2; i <= n; i++) {
27 if (isPrime(i)) {
28 printf("%d ", i);
29 }
30 }
31 printf("\n");
32
33 return 0;
34}
$ ./prime_1_to_n

Enter N: 50\nPrime numbers from 1 to 50:\n2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

📖 Code Explanation

CodeExplanation
bool isPrime(int num)Function that returns true if num is prime
if (num <= 1)Numbers ≤ 1 are not prime
if (num % 2 == 0)Even numbers (except 2) are not prime
i * i <= numOnly check up to √num for efficiency
i += 2Skip even numbers (check only odd)

Simple Version (Without Function)

prime_simple.c
C
1#include <stdio.h>
2
3int main() {
4 int n, i, j, isPrime;
5
6 printf("Enter N: ");
7 scanf("%d", &n);
8
9 printf("Prime numbers from 1 to %d:\n", n);
10
11 for (i = 2; i <= n; i++) {
12 isPrime = 1; // Assume prime
13
14 for (j = 2; j * j <= i; j++) {
15 if (i % j == 0) {
16 isPrime = 0; // Not prime
17 break;
18 }
19 }
20
21 if (isPrime)
22 printf("%d ", i);
23 }
24
25 return 0;
26}

📊 Prime Numbers Reference

RangeCountPrime Numbers
1 - 1042, 3, 5, 7
1 - 50152, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
1 - 10025+ 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

⚡ Complexity Analysis

Time Complexity

O(N × √N)

Space Complexity

O(1)

🎯 Key Takeaways

Start checking from 2 (smallest prime)
Check divisibility up to √n only
Skip even numbers for optimization
Use a helper function for cleaner code

Want to Learn More?

Explore our comprehensive tutorials for in-depth explanations of C programming concepts.

Browse Tutorials
Back to All Examples