Write a C program for all Prime number between 1 to N.

C program for Prime number between 1 to N. first we know what is prime number? than discuss about how to write our program?

Prime number is number which is only divided by 1 or itself that means it has only two factors.

  • For example: 2,3,5,7,11,13,17…

Observe the above example, all the number mention in above example it has only two factors, so now discuss how to start our program?

First fall we print the statement and get the number from user using scanf function. This is very first step and then write program to print prime number. so now write program and take a look of output.

before we write program you should know about-

  • loop
  • nested-loop
  • if-else

SOURCE CODE:

#include<stdio.h>
int main(){
    int n,i,j;
    printf("enter a number to get all prime number between 1 to n:");
    scanf("%d",&n);
    for(i=2;i<n;i++){
        for(j=2;j<i;j++){
            if(i%j==0){
                break;
            }
        }
        if(j==i){
            printf("%d\t",i);
        }
    }
    return 0;
}

OUTPUT:

enter a number to get all prime number between 1 to n:20
2       3       5       7       11      13      17      19

SECOND OUTPUT:

enter a number to get all prime number between 1 to n:100
2       3       5       7       11      13      17      19     23      29      31      37      41      43      47      53      59      61      67      71      73      79      83       89      97

DISCUSS A PROGRAM:

First we include stdio.h library, which is inbuilt library in c language. Then write program in  main function because we know every program in C starting with main function. After that print a statement using printf function and take input from user using scanf function.

Then after we take nested for loop which started from 2 because prime number divisible by 1. First loop is less then the number input by user and second loop is less then first loop because in this program we perform division from 1st loop to 2nd loop.

There is one logic that is if i divided by j (where j perform division by all then number less then i) then the number is not a prime number that why we break the loop but if i=j that means second loop is not run at least once and if its true then that number is prime number. so we print that number using printf.    

                   more practicals of c language

                       learn c language here

0 Comments