C PROGRAM
Program to print prime numbers within a limit |C Program|
Introduction
Prime numbers are a fascinating aspect of number theory, and identifying them is a common task in programming. In this blog post, we'll explore a C program that generates prime numbers up to a user-specified limit. Understanding how to identify and generate prime numbers is fundamental for anyone delving into the world of computer programming.
Code
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,k,j,f;
clrscr();
printf("enter a limit : ");
scanf("%d",&n);
printf("prime number are\n");
for(i=1;i<n;i++)
{
f=0;
for(j=1;j<=n;j++)
{
f(i%j==0)
f++;
}
if(f==2)
printf("%d\n",i);
}
getch();
}
Output
enter a linit : 20
prime number are
2
3
5
7
11
13
17
19
Explanation
1. Header Files:
The program includes the standard input/output header <stdio.h> and the console I/O header <conio.h>.
2. Main Function:
The main function initiates the program.
Users are prompted to enter a limit (n) up to which prime numbers will be generated.
3. Prime Number Generation:
The program utilizes nested for loops to check the divisibility of each number within the limit (i) by all numbers from 1 to n.
The variable f counts the number of divisors for each number.
If a number has exactly two divisors, it is considered prime, and it is printed.
4. Result Display:
The program prints the prime numbers within the specified limit.
5. User Interaction:
Users receive clear feedback about the limit they entered and the corresponding prime numbers generated.
Conclusion
This C program provides a straightforward implementation of generating prime numbers within a given limit. While the code is clear and functional, it's important to note that more efficient algorithms, such as the Sieve of Eratosthenes, exist for larger datasets.
Experiment with different limits, analyze the flow of the program, and consider optimizations or alternative approaches. Understanding prime numbers is a foundational concept in number theory and has applications in various areas of computer science.
Post a Comment
0 Comments