How does a C program to check prime number work?

 Courtesy: Programiz.com


In the program, a for loop is iterated from i = 2 to i < n/2.

In each iteration, whether n is perfectly divisible by i is checked using:

if (n % i == 0) {
    flag = 1;
    break;
}

If n is perfectly divisible by in is not a prime number. In this case, flag is set to 1, and the loop is terminated using the break statement.

Notice that we have initialized flag as 0 during the start of our program.

So, if n is a prime number after the loop, flag will still be 0. However, if n is a non-prime number, flag will be 1.

Comments

Popular posts from this blog

C program to read and display book information using structure

Function prototype and definition

Actual and Formal Parameters