Loop Exercises
Write a program in C to input a number and check whether the number is prime number or not using for loop. How to check prime numbers using loop in C programming. Logic to check prime numbers in C programming.
Required knowledge
Basic C programming, If else, For loop
What is Prime number?
Prime numbers are the positive integers greater than 1 that is only divisible by 1 and self. For example: 2, 3, 5, 7, 11 etc...
Logic to check prime number
There are several efficient algorithms for prime test. For this post I am implementing the simplest and easiest algorithm for beginners. If the number is divisible by any number in between 2 to n-1. Then it is composite number otherwise prime.
Step by step descriptive logic to check prime number.
- Input a number from user. Store it in some variable say num.
- Declare and initialize another variable say isPrime = 1. isPrime variable is used as a notification or flag variable. Assigning 0 means number is composite and 1 means prime.
- Run a loop from 2 to num/2, increment 1 in each iteration. The loop structure should be like for(i=2; i<=num/2; i++).
- Check, divisibility of the number i.e. if(num%i == 0) then, the number is not prime.
Set isPrime = 0 indicating number is not prime and terminate from loop. - Outside the loop check the current value of isPrime. According to our assumption if it is equal to 1 then the number is prime otherwise composite.
Program to check prime number
/**
* C program to whether a number is prime number or not
*/
#include <stdio.h>
int main()
{
int i, num, isPrime;
/*
* isPrime is used as flag variable.
* If isPrime = 0, then number is composite
* else if isPrime = 1, then number is prime.
* Initially I have assumed the number as prime.
*/
isPrime = 1;
/* Input a number from user */
printf("Enter any number to check prime: ");
scanf("%d", &num);
for(i=2; i<=num/2; i++)
{
/* Check divisibility of num */
if(num%i==0)
{
/* Set isPrime to 0 indicating it as composite number */
isPrime = 0;
/* Terminate from loop */
break;
}
}
/*
* If isPrime contains 1 then it is prime
*/
if(isPrime == 1)
{
printf("%d is prime number", num);
}
else
{
printf("%d is composite number", num);
}
return 0;
}
Output
Enter any number to check prime: 7
7 is prime number
