Menu
×
Tutorials Ms Word Tutorial Ms Excel Tutorial Ms PowerPoint Tutorial C Language Tutorial C++ Tutorial C Sharp Tutorial Visual Basic Tutorial HTML Tutorial CSS Tutorial JavaScript Tutorial WordPress Tutorial
     ❯   

ADVERTISEMENT

Max Prime Number Under Given Number

This C program is designed to find the maximum prime number below a user-entered number.


#include<stdio.h>
main()
{
  int num,i,count=0,j,maxPrime=1;
  printf("Enter a number \n");
  scanf("%d",&num);
  for(i=1;i<=num;i++)
  {
    count=0;
    for(j=1;j<=i;j++)
    {
      if(i%j==0)
      {
        count++;
      }
    }
    if(count==2)
    {
      if(maxPrime<i)
      {
       maxPrime=i;
      }
    }
  }
 
  printf("Maximum Prime number below %d is %d\n",num,maxPrime);
}
C Programming Examples
OUTPUT
Enter a number
10000
Maximum Prime number below 10000 is 9973
C Programming Examples

Let’s break down the code step by step:

  1. Include Header File:
   #include<stdio.h>

This line includes the standard input-output library in the program, which is necessary for using functions like printf and scanf.

  1. main() Function:
   main()

The main function is the starting point of the program.

  1. Variable Declaration:
   int num, i, count = 0, j, maxPrime = 1;

These variables are used to store the user input (num), loop counters (i and j), a counter for factors (count), and the maximum prime number found (maxPrime).

  1. User Input:
   printf("Enter a number \n");
   scanf("%d", &num);

The user is prompted to enter a number, and the input is stored in the variable num.

  1. Prime Number Check:
   for(i = 1; i <= num; i++)
   {
      count = 0;
      for(j = 1; j <= i; j++)
      {
         if(i % j == 0)
         {
            count++;
         }
      }
      if(count == 2)
      {
         if(maxPrime < i)
         {
            maxPrime = i;
         }
      }
   }

The program uses nested loops to iterate through numbers from 1 to the user-entered number (num). The inner loop checks for factors of the current number (i), and if the count of factors is exactly 2 (indicating it’s a prime number), the program compares it with the current maxPrime and updates it if the new prime number found is greater.

  1. Print Result:
   printf("Maximum Prime number below %d is %d\n", num, maxPrime);

Finally, the program prints the result, indicating the maximum prime number below the user-entered number.

The program employs nested loops to check for prime numbers below a user-entered number. It keeps track of the maximum prime number found during the iteration and prints the result at the end.

Spread the love
Scroll to Top
Scroll to Top