C Program to print Prime numbers from 1 to n with explanation and flowchart

C Program to print Prime numbers from 1 to n

  prime number is a number that is divisible only by itself and 1, below is a program which will print prime numbers from 1 to entered range, explanation of every line is given in comments also at end we have added a flowchart by which you can easily understand the working of this c program.
If we want program for specific range then just remove first printf and scanf statement and replace n with that range

example: prime numbers from 1 to 100

for(num=1;num<=100;num++)

Program:


#include<stdio.h>
#include<conio.h>
void main()
{
int num,i,n;
printf("Enter the range: ");
scanf("%d",&n);

printf("Prime numbers between 1 to %d: \n\n",n);
printf("2\n"); /* we print 2 since 2 is 1st obvious prime number */

for(num=1;num<=n;num++) /* for loop which will run 1000 time */
{
i=2;
while(i<=num-1)
   {
    if(num%i==0) /* if reminder is zero then its not a prime number therefore we break the execution and check next number */
          {
          break; /* to stop execution  there itself and increment value of variable i */
          }
    else if(i==num-1) /* checking i equal to num-1, if true then value in num will be printed which will be Prime number */
             {
             printf("%d\n",num); /* print prime number which is stored in variable num */
             }
    i++; /* incrementing i so that we can keep on checking the next numbers */
     } /* C Program to print Prime numbers 1 to n by SlashMyCode.com */
}
    getch();
}


Output:

output of C Program to print Prime numbers from 1 to n

Flowchart:
Note: this flowchart is for range 1 to 1000
flowchart of C Program to print Prime numbers from 1 to n
Click on image to enlarge


Sharing is awesome 😉😉

No comments:

Post a Comment

Feel free to ask us any question regarding this post