Print the Prime or Composite Numbers Using For Loop in C


This program is written in the C programming language and is used to check if a given number is a prime number or not. The program starts by including the standard input/output library (stdio.h) and then defines a main function. Within the main function, the program declares four variables: "i", "n", "prime". The variable "i" is used to store the number entered by the user, "n" is used as a loop counter, "prime" is used to count the number of factors of the entered number.

The program then prompts the user to enter a number using the "printf" function and stores the value in the variable "i" using the "scanf" function. Next, the program uses a "for" loop with the counter variable "n" to iterate from 1 to the value of "i". Within this loop, it uses an if statement to check if the current value of "i" divided by "n" has a remainder of 0 or not. If the remainder is 0, it means that the number is divisible by n which means it is not a prime number. If it is divisible by n then the program increments the value of the "prime" variable by 1.

After the loop has finished, if the value of prime variable is 0, it means that the number entered is prime as it doesn't have any factors other than 1 and itself. The program then uses the "printf" function to print that the number is prime. If the value of prime variable is not 0, it means that the number entered is not prime as it has more than 2 factors. The program then uses the "printf" function to print that the number is not prime. Finally, the program returns 0 to indicate that the program has completed successfully.

Source Code

#include<stdio.h>
int main()
{
  int i,n,a,prime=0;
  printf("\nEnter the number:");
  scanf("%d",&i);
  for(n=1;n<i;n++)
  {
     if(i%n==0)
     {
        prime++;
     }
  }
  if(prime==0)
  {
     printf("\nThis number is Not Prime");
  }
  else
  {
     printf("\nThis number is Prime");
  }
  return 0;
}
To download raw file Click Here

Output

Enter the number:41
This number is Prime

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C