Printing Prime Numbers up to a Given Limit in C Programming


This program is written in the C programming language and is used to print all the prime numbers up to a given limit. The program starts by including the conio.h library, which is not a standard library of C, it's a non-standard library and is used for console input/output. Then, it defines the main function. Within the main function, the program declares four variables: "i", "j", "n", and "prime".

The variable "n" is used to store the value entered by the user, while "i" and "j" are used as loop counters in the program. The variable "prime" is used to store the number of times a number is divisible by any number other than 1 and itself, if a number is divisible by any number other than 1 and itself it means the number is not prime.

The program then prompts the user to enter a value using the "printf" function and stores the value in the variable "n" using the "scanf" function. Next, the program uses a "for" loop with the counter variable "i" to iterate from 1 to the value of "n". Within this loop, another "for" loop is used with the counter variable "j" to iterate from 2 to "i-1". The inner for loop checks if i is divisible by any number other than 1 and itself using if statement. If it is divisible, the variable prime will be incremented.

After the inner loop, if the value of prime is 0, it means that the number is prime and the program uses the "printf" function to print the number. Finally, the program returns 0 to indicate that the program has completed successfully.

Source Code

#include<conio.h>
int main()
{
  int i,j,n,prime=0;
  printf("\nEnter The Ending Value:");
  scanf("%d",&n);
  for(i=1;i<=n;i++)
  {
     prime=0;
     for(j=2;j<i;j++)
     {
       if(i%j==0)
       {
         prime++;
       }
     }
     if(prime==0)
     {
        printf("\n%d",i);
     }
  }
  return 0;
}
To download raw file Click Here

Output

Enter the Ending value : 20
1
2
3
5
7
11
13
17
19

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C