If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, you can use a while loop to find the next prime number after a given number. You can start by incrementing the given number by 1 and then use a for loop to check if the number is prime or not.
Here's an example of C code that finds the next prime number after a given number:
Copy code
#include <stdio.h>
int main() {
int n, i,flag=0;
printf("Enter a positive integer: ");
scanf("%d", &n);
n++;
while(1) {
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
flag=1;
break;
}
}
if(flag==0) {
printf("The next prime number after %d is %d.\n",n-1,n);
return 0;
}
else{
flag=0;
n++;
}
}
return 0;
}
This code prompts the user to enter a positive integer, increments it by 1 and uses a while loop to check if the incremented number is prime or not by using a for loop. It checks if the incremented number is divisible by any number from 2 to half of the number. If it is not divisible by any, it prints the incremented number as next prime number after the entered number and exits the loop. If not, increments the number and check again until it finds the next prime number.
Comments: 0