C Program to Print Prime Numbers from 1 to n

Written By: Nathan Kellert

Posted On:

Prime numbers are those numbers greater than 1 that are only divisible by 1 and themselves. For example, 2, 3, 5, 7, and 11 are prime numbers. Now, let’s write a C program to print all the prime numbers from 1 to a given number n.

The Code

#include <stdio.h>

// Function to check if a number is prime
int isPrime(int num) {
    if (num <= 1) {
        return 0; // 0 and 1 are not prime numbers
    }
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return 0; // If divisible, it's not prime
        }
    }
    return 1; // If not divisible, it is prime
}

int main() {
    int n;

    // Ask the user for input
    printf("Enter a number: ");
    scanf("%d", &n);

    printf("Prime numbers from 1 to %d are:\n", n);

    // Loop to check each number from 1 to n
    for (int i = 1; i <= n; i++) {
        if (isPrime(i)) {
            printf("%d ", i); // Print prime number
        }
    }

    return 0;
}

How It Works

  1. isPrime function: This function checks if a number is prime. It returns 0 if the number is not prime and 1 if it is prime.
    • The function works by trying to divide the number by all integers from 2 up to the square root of the number. If it finds any divisor, it returns 0 (not prime). Otherwise, it returns 1 (prime).
  2. Main Function:
    • We ask the user to input a number n, which defines the range from 1 to n for which we want to print prime numbers.
    • Then, the program loops through all numbers from 1 to n, checks if each number is prime using the isPrime function, and prints it if it is prime.

Example Output

Enter a number: 30
Prime numbers from 1 to 30 are:
2 3 5 7 11 13 17 19 23 29

How to Improve

You can improve this program by:

  • Optimizing the prime check further, maybe by skipping even numbers after checking for 2.
  • Printing prime numbers in a more user-friendly format (e.g., in rows or columns).

Conclusion

That’s all! Now you can use this program to print prime numbers for any given value of n. It’s a simple approach, but perfect to help you understand how prime numbers work and how to check them in a loop.

Photo of author

Nathan Kellert

Nathan Kellert is a skilled coder with a passion for solving complex computer coding and technical issues. He leverages his expertise to create innovative solutions and troubleshoot challenges efficiently.

Leave a Comment