Complementary task for topic: 2
M Nemeth · 2023-08-29 15:21:04.607221'
Loops: While: Prime count
Loops: While: Prime count
Task: Determine the number of prime numbers in a range:
Write a C program that prompts the user to enter a positive integer as the upper limit of a range and determines the number of prime numbers within that range using a while loop. Display the result using printf().
Hint: You need to sweep on numbers and check on each element if it is a prime or not. As the prime chececk is again a loop, you will need a nested loop
Solution
#include
int main() {
int upperLimit;
printf("Enter the upper limit of the range: ");
scanf("%d", &upperLimit);
if (upperLimit < 2) {
printf("Invalid input. Please enter a positive integer greater than or equal to 2.\n");
return 0;
}
int count = 0;
int num = 2;
while (num <= upperLimit) {
int isPrime = 1;
int divisor = 2;
while (divisor <= num / 2) {
if (num % divisor == 0) {
isPrime = 0;
break;
}
divisor++;
}
if (isPrime) {
count++;
}
num++;
}
printf("The number of prime numbers in the range 2 to %d is %d.\n", upperLimit, count);
return 0;
}
Explanation
In this example, the program uses printf() to prompt the user to enter the upper limit of the range. The scanf() function is used to scan the input from the user and store it in the upperLimit variable. The program checks if the upper limit is less than 2. If it is, it prints an error message and terminates the program. Otherwise, it initializes the count variable to 0 and the num variable to 2. The outer while loop continues as long as num is less than or equal to the upper limit. In each iteration, it initializes the isPrime variable to 1 and the divisor variable to 2. The inner while loop continues as long as divisor is less than or equal to half of num. It checks if num is divisible by divisor, and if so, sets isPrime to 0 and breaks the loop. If isPrime is still 1 after the inner loop, it increments the count variable. Finally, it increments num and repeats the process until num exceeds the upper limit. Once the outer loop terminates, it uses printf() to display the result.