0

Writing a c program where the objective is to get the user's input a number of times, and when the user has input a specific age, the loop stops and outputs the average, smallest and largest of all the values the user just input; however, when determining the largest/smallest/average of the ages, the program must ignore the age that stops the while loop. I am only able to use a single loop. The only issue I am having is with the output. It is not ignoring the specific age and giving me wonky numbers. Here is a piece of my coding:

 #include <stdio.h>
 int age, avAge, minAge, maxAge, sum;
 sum = 0;
//here is where I get the user input
    while (age != -1){
              printf("Please enter age: \n");
              scanf("%d", &age);
//here is where I try to calculate the average
              sum += age;
              avAge = sum / age;
//here is where I placed restrictions on the ages the user can input
              if (age >= 0 && age <= 100)
                   printf("Nice try!\n");
//here is where I try to get the largest/smallest in order
              if (age < minAge)
                   minAge = age;
              if (age > maxAge)
                   maxAge = age;

//here is where I output if the user inputs a 0
              else ( age == -1){
              printf("Smallest: %d\n", minAge);  
              printf("Largest: %d\n", maxAge);
              printf("Average: %d\n", avAge)

  return 0;
  }

Please forgive my coding format, I'm on my phone since I'm running an uninstalled ubuntu on my computer. I just want an idea of what I should use to keep the program from using the 0 as the minAge. Since I can only use one loop, my options are limited I think. Please keep in mind I'm very new at c so I apologize for any ignorance on my part. Thank you.

19
  • 2
    you've got the wrong logic for average age... avAge = sum of all ages / total number of ages Commented Feb 11, 2017 at 5:32
  • 1
    It's very difficult to assess incomplete code. Please provide a minimal reproducible example including exact input, expected output and actual output. Commented Feb 11, 2017 at 5:34
  • 1
    if (age >= 0 && age <= 100) is suspicious, surely that's meant to be if (age < 0 && age >= 100) ? Commented Feb 11, 2017 at 5:36
  • 2
    age, minAge and maxAge are all used whilst uninitialised. Commented Feb 11, 2017 at 5:50
  • 1
    We told you. Using uninitialised variables results in undefined behaviour. Is that not clear? At least try init the vars and re-test. Commented Feb 11, 2017 at 5:54

3 Answers 3

1

I think an infinite loop makes some level of sense here, I've moved your print result statements out of the loop so they will still only execute once the user is done inputting age s. I've also corrected if (age >= 0 && age <= 100) to if (age < -1 && age > 100) and correctly initialised all variables before use with some added comments, if you've any further questions just drop a comment :)

#include <stdio.h>
#include <limits.h> // for INT_MAX 
int main(void) 
{
    int age, avAge = 0, minAge = INT_MAX, maxAge = 0, sum = 0, avgCounter = 1; // avgCounter is the amount of times the loop has ran

    while( 1 ) //infinite loop broken if age == -1
    {
        printf("Please enter age: \n");
        scanf("%d", &age);

        if( age == -1 )
            break;   // exit loop
        else if (age < -1 && age > 100)
           printf("Nice try!\n"); // could add continue here in order to not skew the min/max and average age variables.
        else if (age < minAge)
           minAge = age;
        else if (age > maxAge)
           maxAge = age;
        sum += age;
        avAge = sum / avgCounter;
        avgCounter++;
    } 

    printf("Smallest: %d\n", minAge == INT_MAX? 0 : minAge); // incase the user enters -1 straight away  
    printf("Largest: %d\n", maxAge);
    printf("Average: %d\n", avAge);
}

NOTE: The actual reason for seeing "wonky numbers" is probably due to undefined behaviour thanks to uninitialised variables, you must always make sure they are initialised before attempting to read/use them.

Sign up to request clarification or add additional context in comments.

4 Comments

YOU DID IT. That's awesome. I actually do have a few questions: (1) How do you know when to use int main() and int main (void). I've seen the book/websites do both and they don't explain it. (2)Also, why did you set the avgCounter to 1? (3)Why did you put the 1 in the while ()? I understand it's to break the infinite loop, so would the reasoning behind the logic of this working is because it's the abs value of -1? I'm just trying to understand how it works. (4)When you do the avgCounter++, is that incrementing it like in java? (5)Why did you include <limits.h>? What is its purpose?
this is actually really great. Thank you so much.
Also, I assumed that because it was a variable given by user input, the user would initialize it by inputting the number. Stupid, I know. Thank you for correcting me. Thank you for being nice.
(1) Normally I wouldn't care, it's just what my editor defaults to although in practice it's to prevent any arguments being passed when main is invoked. (2) To prevent division by 0. (3) while(1) is an idiomatic way to create an infinite loop as 1 is true and so the "condition" in while(condition) is always true. (4) Yes! (5) So I can use the INT_MAX macro. Hope it helps! :)
0

Edit : There are too many small errors in you current code both logical and syntax related. The below code works as expected by your requirement.

 #include <stdio.h>

 int main(){
 int age, avAge, minAge, maxAge, sum;
 minAge = 100000 ; // some very large number
 maxAge = -1;   // initailize with min possible age
 sum = 0;
 int iteration = 0 ; // no. of times the loops run with valid input from user
    do{
              printf("Please enter age: , -1 to quit \n");
              scanf("%d", &age);

              if (age >= 0 && age <= 100) {
                   printf("Nice try!\n");
                   iteration ++; 
                   sum += age;
                   avAge = sum / age;   

                 if (age < minAge)
                   minAge = age;

                 if (age > maxAge)
                   maxAge = age;
              }
              else {
                printf("Smallest: %d\n", minAge);  
                printf("Largest: %d\n", maxAge);
                printf("Average: %d\n", avAge);
                break ;
              }     
    }
    while( age > 0 && age <= 100) ;

    return 0;
  }

Working example on ideone.

1 Comment

I tried this exact thing and it just kept looping and wouldn't print anything.
0

Assuming valid age is in the range (0, 100], here is an implementation:

#include <stdio.h>

int main(void) {
    int age, minAge, maxAge, sum, avAge;
    sum = 0;
    int i = 0;     // counts the number of ages read

    printf("Please enter age: ");
    while (scanf("%d", &age)) {
        // if age is in range (0, 100], consider valid
        //   and invalid otherwise
        if (age > 0 && age <= 100) {
            // calculate sum
            sum += age;

            // if this is the first loop round (i == 0), initialize
            //   both minAge & maxAge to 'age', since they
            //   don't yet have a valid value
            if (i == 0) {
                minAge = age;
                maxAge = age;
                ++i;
            } else {
                if (age < minAge) {
                    minAge = age;
                }
                if (age > maxAge) {
                    maxAge = age;
                }
                ++i;
            }
        } else if (age == 0) {
            // if age is zero, break/exit loop
            // zero can be changed to any invalid value (eg. -1)
            break;
        } else {
            printf("Nice try!\n");
        }
        printf("Please enter age: ");
    }

    // calculate average (outside loop)
    // average = sum / number of ages read
    avAge = sum / i;

    // print summary
    printf("Smallest: %d\n", minAge);
    printf("Largest: %d\n", maxAge);
    printf("Average: %d\n", avAge);

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.