Here's a C program that finds the count of prime numbers between two user-input numbers (n and m) with proper input sanitization and error handling:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
// Function to check if a number is prime
bool isPrime(int num) {
if (num <= 1) return false;
if (num <= 3) return true;
// Check up to square root of num
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
// Function to validate if input string is a valid positive integer
bool isValidNumber(const char *str) {
if (str == NULL || *str == '\0') return false;
// Check each character
for (int i = 0; str[i] != '\0'; i++) {
if (!isdigit(str[i])) return false;
}
return true;
}
// Function to get valid integer input from user
bool getValidInput(const char *prompt, int *number) {
char input[100];
printf("%s", prompt);
if (fgets(input, sizeof(input), stdin) == NULL) {
return false;
}
// Remove newline character if present
size_t len = strlen(input);
if (len > 0 && input[len-1] == '\n') {
input[len-1] = '\0';
}
// Validate input
if (!isValidNumber(input)) {
return false;
}
// Convert to integer
*number = atoi(input);
return true;
}
int main() {
int n, m;
bool validInput = false;
// Get and validate first number (n)
do {
validInput = getValidInput("Enter the lower bound (n): ", &n);
if (!validInput) {
printf("Error: Please enter a valid positive integer.\n");
}
} while (!validInput);
// Get and validate second number (m)
do {
validInput = getValidInput("Enter the upper bound (m): ", &m);
if (!validInput) {
printf("Error: Please enter a valid positive integer.\n");
}
else if (m < n) {
printf("Error: Upper bound (m) must be greater than or equal to lower bound (n).\n");
validInput = false;
}
} while (!validInput);
// Count prime numbers between n and m
int primeCount = 0;
printf("\nPrime numbers between %d and %d are:\n", n, m);
for (int i = n; i <= m; i++) {
if (isPrime(i)) {
printf("%d ", i);
primeCount++;
}
}
printf("\n");
// Display result
if (primeCount == 0) {
printf("There are no prime numbers between %d and %d.\n", n, m);
} else {
printf("Total count of prime numbers between %d and %d: %d\n", n, m, primeCount);
}
return 0;
}
This program includes the following features and error handling:
-
Input Validation:
- Uses
isValidNumber() to check if the input contains only digits
- Ensures inputs are positive integers
- Checks if m is greater than or equal to n
-
Error Handling:
- Handles invalid input (non-numeric characters, empty input)
- Provides clear error messages
- Continues prompting until valid input is received
-
Prime Number Checking:
- Uses an efficient
isPrime() function that:
- Handles edge cases (numbers ≤ 1)
- Uses optimization by checking only up to square root
- Returns boolean result
-
User Interface:
- Clear prompts for input
- Displays all prime numbers found
- Shows the total count
- Handles the case when no prime numbers are found
-
Safety Features:
- Uses
fgets() instead of scanf() to prevent buffer overflow
- Properly handles newline characters
- Includes necessary header files
Example usage:
Enter the lower bound (n): 10
Enter the upper bound (m): 30
Prime numbers between 10 and 30 are:
11 13 17 19 23 29
Total count of prime numbers between 10 and 30: 6
Enter the lower bound (n): abc
Error: Please enter a valid positive integer.
Enter the lower bound (n): 30
Enter the upper bound (m): 20
Error: Upper bound (m) must be greater than or equal to lower bound (n).
Enter the upper bound (m): 40
The program will continue to prompt for valid input if the user enters:
- Non-numeric characters
- Negative numbers
- Empty input
- When m is less than n
This implementation is robust, user-friendly, and handles various edge cases while providing clear feedback to the user.