Index
1. First C program 2. Data Types in C 3. Format Specifiers in C 4. Operators in C 5. Operator Precedence, Associativity of Operators 6. Increment and Decrement Operators 7. Bitwise Operators in C 8. Ternary Operators in C 9. Switch Statement 10. Functions in C 11. Call by value and Call by Reference 12. Storage Classes in C 13. Array in C 14. Two Dimensional Arrays 15. Strings in C 16. String Functions in C 17. Structure in C 18. Union in C 19. Dynamic Memory Allocation in C 20. C Programming Tutorial: Understanding Comments and Identifiers with Code ExamplesWrite a C program to check whether a given number is prime or not
A prime number is a number greater than 1 with only two factors – themselves and 1.
A prime number cannot be divided by any other numbers without leaving a remainder.
An example of a prime number is 13. It can only be divided by 1 and 13. Dividing a prime number by another number results in numbers left over e.g. 13 ÷ 6 = 2 remainder 1.
15 is not an example of a prime number because it can be divided by 5 and 3 as well as by itself and 1.
C program to check whether a given number is prime or not.
#include int main() { int number = 7; char flag = 0; for(int i = 2; i <= (number/2); i++) { if(number % i == 0) { flag = 1; break; } } if (number == 1) { printf("1 is neither prime nor composite."); } else { if(flag == 0) printf(" %d is a prime number.", number); else printf(" %d is not a prime number.", number); } return 0; }
Output
7 is a prime number.
In this program, a loop is iterated from 2 to number/2. In each iteration, using the condition (number % i) it is checked whether a given number is perfectly divisible by i.
If a number is perfectly divisible by i, then the flag is set to 1 and break. After iteration, we will check whether a given number is 1 or not. if it is 1, the number is considered as a non-prime number else, if the flag is 0, then the given number is a prime number else the number is not a prime number.
Previous Next
NEWSLETTER
Coding Bytes by Codzify
Welcome to Coding Bytes, your weekly source for the latest coding tutorials and insights in small byte sized content.
Join 798+ Subscribers
Subscribe on LinkedInMonetize your Passion Today!
Join Codzify Affiliate Program, Earn 30% Commission on Course Sales, Get ₹449.7 or $5.41 per course Sale! No Follower Requirement. Monetize Your Passion Today!
Register NOW!Codzify Youtube Channel
Ready to level up your Full Stack App development Skills? Check out Codzify Youtube Channel for interatcive video content.
Subscribe Codzify