Christian Galle
Christian Galle

Reputation: 21

Issue with while loop in C - Rejects input, but then accepts same input second time around

I'm trying to get this program to run properly. It prompts user for a nonzero integer, if a nonzero integer is not entered, the while loop should keep prompting user until a nonzero integer is entered.

Then, it takes the integer and uses that as the amount of double entries the user may enter. The program then calls a function that takes the maximum, minimum, and mean of these user-determined amount of double values.

My issue is that even if I enter a nonzero integer, it rejects it and loops the prompt a second time. But, it accepts the nonzero integer the second time. Code below. Thanks!

#include<stdio.h>

void mmm (int n);

int main()
{
    int num;

    printf("Enter a positive nonzero integer: ");
    scanf("%d", &num);

    while(num < 1);
    {
        printf("Invalid number!\n");
        printf("Enter a positive nonzero integer: ");
        scanf("%d", &num);
    }

    mmm(num);

    return 0;
}

void mmm (int n)
{
    double min, max, mean, sum, entry;
    int i;

    printf("***** MIN MAX and MEAN *****\n");
    printf("Enter %d numbers separated by spaces: ", n);

    sum = 0;
    for(i = 1; i <= n ; i++)
    {
        scanf("%lf", &entry);
        sum += entry;



        if(i == 1)
        {
            max = entry;
            min = entry;
        }

        if(max < entry) 
        max = entry; 

        if(min > entry)
        min = entry;

    }

    mean = sum/n;

    printf("Minimum, maximum, and mean of the %d numbers: %.2lf, %.2lf, %.2lf\n", n, min, max, mean);

}

Upvotes: 0

Views: 63

Answers (1)

Christian Galle
Christian Galle

Reputation: 21

OK I fixed this by implementing a do-while loop in main:

#include<stdio.h>

void mmm (int n);

int main()
{
    int num;

    do{
        printf("Enter a positive nonzero integer: ");
        scanf("%d", &num);
    }

    while (num <= 0);


    mmm(num);

    return 0;
}

Upvotes: 1

Related Questions