C program to check whether a number is prime number or not

Write a program in C to enter any number and check whether the number is prime number or not using for loop. How to check prime numbers using loop in C programming. Prime condition check using loop in C program.

Enter any number: 17
Output: Number is Prime number

Also see how to write same program using concept of function - C program to check prime number using functions.

Required knowledge:

Basic C programming, If else, For loop

Prime numbers

Prime numbers are the positive integers greater than 1 that is only divisible by 1 and self. For example: 2, 3, 5, 7, 11 etc...

Program to check prime number using loop

 * C program to whether a number is Prime Number or not

#include <stdio.h>

int main()
    int i, n, flag;

    //Flag is used as notification. Initially we have supposed that the number is prime.
    flag = 1; 

    /* Reads a number from user */
    printf("Enter any number to check prime: ");
    scanf("%d", &n);

    for(i=2; i<=n/2; i++)
         * If the number is divisible by any number 
         * other than 1 and self then it is not prime
            flag = 0;

     * If flag contains 1 then it is prime
        printf("\n%d is prime number", n);
        printf("\n%d is not prime number", n);

    return 0;

Enter any number to check prime: 7

7 is prime number

Note: break statement is used to terminate the program control flow from inner loop or inner switch. Means whenever break statement is executed inside a loop, the loop will be terminated and the program control will be transferred outside the loop.

Happy coding ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

1 comment: