Write a C Program to Check if a Number is Prime or Not Using For Loop
Write a C Program to Check if a Given Number is Prime or Not Using for Loop
Do you need to check if a given number is a prime number? You can easily do this with the help of the for loop
. Here, we'll explain how to write a C program to check if a given number is prime or not using for loop.
What is a Prime Number?
A prime number is a natural number greater than 1 that has no positive divisors other than one and itself. A prime number is an integer greater than 1 that can only be divided evenly by 1 and itself.
Algorithm to Find a Prime Number
- Start by taking an input number from the user.
- Run a loop from 2 to the input number - 1 and increment the loop counter by 1 each time.
- Check if the input number is exactly divisible by the loop counter.
- If it is divisible, then the number is not a prime number so terminate the loop.
- Otherwise, check if the loop has reached the last iteration i.e. input_number - 1.
- If yes, then the number is a prime number so print "Prime" and terminate the loop.
C Program to Check if a Given Number is Prime or Not Using for Loop
#include<stdio.h>
int main() {
int num, i;
/* Input a positive integer from user */
printf("Enter any number: ");
scanf("%d", &num);
/* Run a loop from 2 to num - 1 */
for(i=2; i<num; i++) {
/* If num is divisible by any number between
2 and num-1, it is not a prime number */
if(num % i == 0) {
printf("%d is not a prime number", num);
break;
}
}
/*
* If num is not divisible by any number between
* 2 and num-1, it is a prime number
*/
if(i == num)
printf("%d is a prime number", num);
return 0;
}
Enter any number: 10
10 is not a prime number
In the above program, we have used for loop to iterate from 2 to input_number-1. We are checking if the reminder of input_number/loop counter is 0. If it is 0, then the number is not a prime number and we terminate the loop. Otherwise, we check if the loop has reached its last iteration. If yes, then the number is a prime number and we print "Prime".
That's it! The above program checks if a given number is a prime number or not using for loop. Try running the program yourself and see what happens!
Top Resources
Prime Numbers: C Program Example and Explanation
Design a function to check the given number is prime or not if prime return 1 else 0
Write a C Program to Check if a Number is Prime or Not Using For Loop
Writing a C Program to Print Prime Numbers Between 50 and 100
write a program to print prime numbers in 10 array elements.
Write a C program to input 10 numbers through the keyword and find the number of prime counts it stores the into a separate array and display it.
Further Reading:
Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!