- Learn C By Examples Time
- Learn C by Examples - Home
- C Examples - Simple Programs
- C Examples - Loops/Iterations
- C Examples - Patterns
- C Examples - Arrays
- C Examples - Strings
- C Examples - Mathematics
- C Examples - Linked List
- C Programming Useful Resources
- Learn C By Examples - Quick Guide
- Learn C By Examples - Resources
- Learn C By Examples - Discussion
Prime Number Program In C
Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example −
7 = 1 × 7
Few prime number are − 1, 2, 3, 5 , 7, 11 etc.
Algorithm
Algorithm of this program is very easy −
START Step 1 → Take integer variable A Step 2 → Divide the variable A with (A-1 to 2) Step 3 → If A is divisible by any value (A-1 to 2) it is not prime Step 4 → Else it is prime STOP
Pseudocode
We can draft a pseudocode of the above algorithm as follows −
procedure prime_number : number FOR loop = 2 to number - 1 check if number is divisible by loop IF divisible RETURN "NOT PRIME" END IF END FOR RETURN "PRIME" end procedure
Implementation
Implementation of this algorithm is given below −
#include <stdio.h> int main() { int loop, number; int prime = 1; number = 11; for(loop = 2; loop < number; loop++) { if((number % loop) == 0) { prime = 0; } } if (prime == 1) printf("%d is prime number.", number); else printf("%d is not a prime number.", number); return 0; }
Output
Output of the program should be −
11 is prime number.
mathematical_programs_in_c.htm
Advertisements