// Arup Guha
// 10/12/2011
// Written in COP 3223 as an illustration of functions.
#include <stdio.h>

int getInput(char greeting[], int lowbound);
int isPrime(int n);

int main(void) {

    // Get the low and high bounds of the search.
    int low = getInput("Enter the low bound.\n", 2);
    int high = getInput("Enter the high bound.\n", low);

    // Print out each prime in range.
    printf("The primes in your range are ");
    int i;
    for (i=low; i<=high; i++) {
        if (isPrime(i))
            printf("%d ", i);
    }
    printf(".\n");

    return 0;
}

// Precondition: n is positive.
// Postcondition: Returns 1 if n is prime, 0 otherwise.
int isPrime(int n) {

    // The smallest prime is 2.
    if (n < 2)
       return 0;

    // Try dividing n by each number from 2 to n-1.
    int div;
    for (div = 2; div < n; div++)
        if (n%div == 0)
            return 0;

    // If we get here, n must be prime.
    return 1;
}

// Precondition: None.
// Postcondition: Prints out greeting and returns the first integer greater
//                than or equal to lowbound entered by the user.
int getInput(char greeting[], int lowbound) {

    int n;

    while (1) {

        // Get a number.
        printf("%s", greeting);
        scanf("%d", &n);

        // Time to get out of the loop.
        if (n >= lowbound)
            break;
        printf("Sorry, your number must be at least %d.\n", lowbound);
    }

    return n;
}

