Check for Prime In C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

In C language, you can use a for loop to check if a number is prime or not. A prime number is a number that is divisible by only 1 and itself. To check if a number is prime, you can start the loop at 2 and increment it until it reaches half of the number. Within the loop, you can use the modulus operator (%), which returns the remainder when one number is divided by another, to check if the number is divisible by the current loop variable. If the remainder is 0, then the number is not a prime number and the loop can be exited.

Here's an example of C code that checks if a number is prime or not:

Copy code

#include <stdio.h> int main() {    int n, i;    printf("Enter a positive integer: ");    scanf("%d", &n);    if (n==1) {        printf("1 is not a prime number.\n");    }    for (i = 2; i <= n / 2; ++i) {        if (n % i == 0) {            printf("%d is not a prime number.\n", n);            return 0;        }    }    printf("%d is a prime number.\n", n);    return 0; }

This code prompts the user to enter a positive integer, checks if it is 1, which is not considered as prime number, and then uses a for loop to iterate through all integers from 2 to half of the entered number. It checks if the entered number is divisible by the current loop variable by using the modulus operator. If it is, it prints that the entered number is not a prime number and exits the loop. If the loop completes without finding a divisor, it prints that the entered number is a prime number.

7. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?