Write a C program to find the first n prime numbers, In this C program example, we will learn Algorithm and C Code to find first n prime number.
Algorithm to find the first n prime numbers
- Declare three variables.
- Take an input.
- Take two for loop and in 2d loop take two if condition, first one for condition and break and the second one for print with an appropriate message.
C program to find first n prime numbers
#include<stdio.h> void main (){ int i,n,j; printf("enter number:"); scanf("%d",&n); for(i=2;i<=n;i++){ for(j=2;j<=i;j++){ if(i%j==0){ break; } } if(i==j){ printf("%d\n",i); } } }
Sample input
Enter any value: 25
Sample output
2
3
5
7
11
13
17
19
23
Explanation of this C program
step 1: Start.
Step 2: Create a header file and include a library on file.
Step 3: Create a void main function.
Step 4: Declare three variable (i,n,j).
Step 5: Then create an input with the help of scanf for taking value from the user to find first n prime number.
Step 6: Create two for loop and give conditions.
Step 7: In the loop create two if statements one for cheak condition and brack it and the second one for print the first n prime number.
Step 8: End.
Output
In this way, we learned how to write a C program to find the first n number.