Travieso Travieso - 8 days ago 6
C Question

How do I adjust this code to allow for an unspecified number of positive integers

I am completely new to programming and I'm currently taking a Intro to programming course. I need to adjust the below code to allow for an unspecified number of positive integers. I've looked this up and it seems to not take the average correctly. Please help. Thank you.

#include <stdio.h>

int main ()
{
/* variable definition: */
int count, value, sum;
double avg;
/* Initialize variables */
count = 0;
sum = 0;
avg = 0.0;
// Loop through to input values
while (count < 20)
{
printf("Enter a positive Integer\n");
scanf("%d", &value);
if (value >= 0) {
sum = sum + value;
count = count + 1;
}
else {
printf("Value must be positive\n");
}
}
// Calculate avg. Need to type cast since two integers will yield an
// integer
avg = (double) sum/count;
printf("average is %lf\n ", avg );
return 0;
}

Answer

You can use infinite loop and check for negative value and the return result of scanf as conditions to break.

Sample code looks like:

    for(;;)
    {
        printf("Enter a positive Integer\n");
        if(scanf("%d", &value) == 1 )
        {
            if (value >= 0) {
                sum = sum + value;
                count = count + 1;
            }
            else {
                printf("Value must be positive\n");
                break;
            }
        }
        else
        {
            break;
        }
    }

Also, your initialization code is ok, but can be done cleaner this way (there is no need to separate between declaration and initialization - you can group them into one line):

    int count = 0, value = 0, sum = 0;
    double avg = 0;