recent posts

Prime number program in C | C programming


Hi, I'm Golam Rabbani. Today I will discuss about prime number.
Greetings! How are you all? Hope everyone is well.
At first we have to know that what is prime number?
A prime number is a whole number greater than 1 whose only factors
are 1 and itself.
Condition of prime number:
  1. It should be whole number.
  2. It should be greater than 1.
  3. It should have only 2 factor. They are 1 and the number itself.
For example: 2, 3, 5, 7, 11, 13, 17, 19, 23 etc.

3 5 7 13
/ \ / \ / \ / \
1 3 1 5 1 7 1 13
Now other number are not prime. I think, everyone thinking about
these number. Why these number are not prime?
For example:
Non prime number:  4, 6, 8, 9, 10, 12, 14, 15, 16 etc.
Description:
Because, the number 4 can be factored as 2*2 and 1*4.
As per the rule of prime number, there should be 2 factors only.


     4  6
  / |  \   / |  | \
 1  2 4  1  2 3   6


They are 1 and the number itself. But, number 4 has 2*2 and 6 has
2*3 also. Like this, all remaining numbers 8, 9, 10, 12, 14, 15, 16
etc.
Let's go. write a this program.

#Prime number program in C language for only check:
#include<stdio.h>
int main(){
    int i,j,n;
    int prime;
    printf("Enter the number: ");
    scanf("%d", &n);
    if(n>=1){
        for(i=1; i<=n; i++){
            prime=0;
            for(j=1; j<=n; j++){
                if(i%j==0){
                    prime++;
                }
            }
        }
        if(prime==2){
            printf("%d is prime number.",n);
        }
        else{
            printf("%d is not prime number.",n);
        }
    }
    else{
        printf("Error! input number should be greater than 1");
    }
    return 0;
}

#Prime number program in C language for viewing all element.
#include<stdio.h>
int main(){
    int i,j,n;
    int prime;
    printf("Enter the number: ");
    scanf("%d", &n);
    if(n>=1){
        for(i=1; i<=n; i++){
            prime=0;
            for(j=1; j<=n; j++){
                if(i%j==0){
                    prime++;
                }
            }
            if(prime==2){
                printf("%d ",i);
            }
        }
    }
    else{
        printf("Error! input number should be greater than 1");
    }
    return 0;
}
Output:


Thank you.
Prime number program in C | C programming Prime number program in C | C programming Reviewed by Golam Rabbani on November 26, 2018 Rating: 5

No comments:

top navigation

Powered by Blogger.