Prime and Composite Numbers C Program Examples
Prime and composite numbers C program examples.
In this article, you will learn how to check prime and composite numbers C program examples.
Example
-----Enter the positive integer number-----
23
23 is the prime number.
What are the prime numbers?
Prime Numbers Sample
If the input integer number exists in the list then the number is a prime otherwise It is the composite number.
You should have knowledge of the following topics in c programming to understand this program:
- C
main()
function - C
printf()
function - C
while
loop - C
For
loop
Source Code
// Prime and Composite Numbers C Program
#include <stdio.h>
int main() {
int x, i = 2, f = 0;
// x - Value of the input integer number
printf("-----Enter the positive integer number-----\n");
scanf("%d", &x);
if (x == 1) {
printf("1 is neither the prime nor the composite number!\n");
} else {
while (i <= x / 2) {
// This is the condition for non-prime
if (x % i == 0) {
f = 1;
break;
}
++i;
}
if (f == 0) {
printf("\n%d is the prime number.\n", x);
} else {
printf("\n%d is not the prime number.\n", x);
}
}
return 0;
}
Output
-----Enter the positive integer number-----
23
23 is the prime number.
Example
In this given program, we have taken input 23
from the user via the system console. Then we applied the standard formula to check the input value that is it a prime number or not.
So after the whole process, It returned that the input value is a prime number.
Prime and Composite Numbers C Program using For loop
// Prime and Composite Numbers C Program using For loop
#include <stdio.h>
int main() {
int x, i, f = 0;
// x - Value of the input integer number
printf("-----Enter the positive integer number-----\n");
scanf("%d", &x);
if (x == 1) {
printf("1 is neither the prime nor the composite number!\n");
} else {
for (i = 2; i <= x / 2; ++i) {
// This is the condition for non-prime
if (x % i == 0) {
f = 1;
break;
}
}
if (f == 0) {
printf("\n%d is the prime number.\n", x);
} else {
printf("\n%d is not the prime number.\n", x);
}
}
return 0;
}
Output
-----Enter the positive integer number-----
30
30 is not the prime number.