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 ExamplesLet’s break down the code step by step:
- 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.
- main() Function:
main()
The main function is the starting point of the program.
- 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).
- 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.
- 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.
- 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.