Write a C Program to Print Prime Numbers From 1 to N.

Prince Patel
By -
0

Write a C Program to Print Prime Numbers From 1 to N.



In this article, prints all the prime numbers from 1 to N without using any structure and function. The program checks each number in the range [1, N] to see if it is a prime number or not.
Here's a C program to Print Prime Numbers From 1 to N:

#include<stdio.h>
#include<conio.h>

void main()
{
    int N, i, j, isPrime;

    // Get the value of N from the user
    printf("Enter a number N: ");
    scanf("%d", &N);

    // Print prime numbers from 1 to N
    printf("Prime numbers from 1 to %d are:\n", N);
    for (i = 2; i <= N; i++) {
        isPrime = 1; // Assume the number is prime initially

        // Check if the number i is divisible by any number from 2 to i-1
        for (j = 2; j < i; j++) {
            if (i % j == 0) {
                isPrime = 0; // If i is divisible by j, then it's not a prime number
                break;
            }
        }

        // If isPrime is still 1, then the number i is prime
        if (isPrime == 1) {
            printf("%d ", i);
        }
    }

    printf("\n");
}

  • We start by declaring the necessary variables, namely 'N' to store the upper limit, 'i' to iterate through the numbers from 2 to N, 'j' to check for divisors, and 'isPrime' to store whether the current number is prime or not.
  • The user is prompted to enter a value for 'N' using scanf.
  • We then use a for loop to iterate through each number from 2 to N. Prime numbers start from 2 since 1 is not considered a prime number.
  • Inside the outer loop, we set 'isPrime' to 1, assuming the current number (i) is prime initially.
  • We use another nested for loop to check if the number i is divisible by any number from 2 to i-1. If i is divisible by any of these numbers, it means i is not a prime number, and we set isPrime to 0 and break out of the inner loop.
  • If isPrime is still 1 after the inner loop, then the number i is prime. We print it using printf.
  • The process continues until the outer loop finishes checking all numbers from 2 to N.
  • The program will then print the prime numbers from 1 to N.

Output:




Note:  This program works fine for smaller values of N, but it may not be efficient for very large N due to the nested loops, which leads to a time complexity of approximately O(N^2). For more efficient prime number generation, you can look into optimized algorithms like the Sieve of Eratosthenes.
Tags:

Post a Comment

0Comments

Post a Comment (0)