Thread: Averaging numbers using a sentinal to stop the loop

  1. #1
    Registered User
    Join Date
    Mar 2014
    Posts
    20

    Question Averaging numbers using a sentinal to stop the loop

    Hello, I did do a search and found two posts on the same program, but they didn't quite get me working like I'd like.

    The assignment: The user will enter either an integer to be averaged or a sentinel of 999 indicating that no more numbers are to be entered. When the sentinel is entered, the program will exit the repetition loop. It will then compute and display the average of numbers entered.

    My program works well ( I think) so far, but I would like for the program to loop back and allow the user to input another integer should they decide to type an invalid character rather than an integer. Currently the program stops if scanf !=1 and averages the numbers correctly.

    There are no comments yet, and the prompts are not finished as this is how I test my programs currently.

    Code:
     #include <stdio.h>
     
     int main()
     {
         
      int uInput;
      int count = 0;
      int sum = 0;
      int sentinel = 999;
      float average;
         
      printf("purpose, %d \n\n", sentinel);
      printf("enter you first number\n");
         
      while (scanf("%d", &uInput)==1)
       {
           if (uInput == sentinel)
           break;
           printf("enter another integer or %d to average the values\n", sentinel);
           sum += uInput;
           count ++;
           printf("the sum is now %d\n", sum);
             
         }
         
         if ( count != 0)
         {
         average= sum/count;
         printf("%d numbers input, %d sum, %.3f average", count, sum, average);
      }
      else 
      printf ("No valid integers were entered, please restart the program and try again");
     
         
             
    
         
      //The section below is to stop the program until a key is pressed.
      fflush(stdin); //clears the input area so you can pause
      printf("\n\n\nPress any key to exit the program."); //prints the message
      getchar(); //force the computer to pause until you press a key
      return 0; //returns a value of 0 if the program works correct    
     }
    I also have been told that last section is garbage, but our instructor said we have to include those lines.

    I can create external functions if this would be easier, but have only written one simple program using pointers and addressing. Any help is greatly appreciated! Thanks in advance!
    Last edited by jesterisdead; 04-12-2014 at 10:29 AM. Reason: I can't speak englsh

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    If the user enters invalid characters, scanf() will stop there. It will return a value (probably zero) but leave the invalid input waiting to be read. So it will loop forever in your code.

    There are various ways to address that, such as using fgets() to read a line of input, and something like sscanf() [note additional s in the name] to interpret that line of input.

    That is an all-or-nothing proposition. If you use fgets() to read from a stream, don't use scanf() or getchar(). The three styles of input (line-oriented, formatted, character-oriented) don't mix well.

    Also, don't use fflush(stdin). It has undefined results.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Mar 2014
    Posts
    20
    Grumpy,
    My code does not loop in my compiler when I input a not integer character, it calculates the average, and so far it has been accurate for me.

    Again, thee fflush(stdin) is required by our instructor, and the 2 lines after it. I'm a student and only have learned what I've read in the book as it is an online course. I have been told by laserlight that these few lines are crap and could give errors, but he wants them.

  4. #4
    Registered User
    Join Date
    Nov 2012
    Posts
    157
    Quote Originally Posted by jesterisdead View Post
    Grumpy,
    Again, thee fflush(stdin) is required by our instructor, and the 2 lines after it. I'm a student and only have learned what I've read in the book as it is an online course. I have been told by laserlight that these few lines are crap and could give errors, but he wants them.
    One of my lecturers insists on using fflush(stdin) and after reading numerous articles on why it shouldn't be used i showed him the c standard.After reading it to himself a couple of times and then out loud a few time's.He muttered some gibberish and left.After a few days he came back to me saying the compiler we use "accepts" this way of flushing the input buffer. I went on to ask him about portability. He hasn't gotten back to me yet, its been over a month so i feel its safe to say he has been educated. I advice you to follow suit although you might want to present yourself a little better than i did(do not ask in presence of your peers....with a cocky smile on your face).
    Last edited by africanwizz; 04-12-2014 at 11:27 AM. Reason: meh..

  5. #5
    Registered User
    Join Date
    Mar 2014
    Posts
    20
    Since I'm taking online courses and my degree is not related to programming, just for my personal Arduino use, I'm not worried about "correcting" him.

    Does everyone else have a problem with my code looping if you input a character? When I input a character, the program stops, does the calculations (correctly on all attempts so far) and exists as if the sentinel was used. We have not gotten into strings or arrays, so I'd like to stick with the methods we've learned to create my code.

  6. #6
    Registered User
    Join Date
    Mar 2014
    Posts
    20
    Anyone? should I just stick with what I have since it's technically not within the scope of the problem? I just hate not having error checking built in.

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by jesterisdead View Post
    Anyone? should I just stick with what I have since it's technically not within the scope of the problem? I just hate not having error checking built in.
    If you read the second line of my previous post, there is an approach to deal with that. The third line of my previous post describes some caveats (things you need to be aware of when addressing problems like you describe).

    No, I'm not going to supply code to do that. I've given you enough pointers so, with a little effort, you would be able to write your own code to address the problem.
    Last edited by grumpy; 04-12-2014 at 04:30 PM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    Registered User
    Join Date
    Mar 2014
    Posts
    20
    Grumpy, if you read my post after that, I can't use strings yet as we have not studied them. I have to use the scanf() function only to get user input.

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    Our FAQ tells you how to clean up input without any messy reliance on stupid tutors or "works for me" compiler behaviour.
    FAQ > Flush the input buffer - Cprogramming.com
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by jesterisdead View Post
    Grumpy, if you read my post after that, I can't use strings yet as we have not studied them. I have to use the scanf() function only to get user input.
    Yeh okay. Technically, it is possible to fix the problem by checking the return value of scanf(), and taking different actions for different return values.

    If your code detects the presence of an unwanted character (say, your scanf() call returns zero) scanf("%c", &some_character) can be used to read that unwanted character, after which you can go back to trying to read an int again. Bear in mind the set of possible return values from scanf() are the same (an error can occur on reading that single character too).


    Practically, unless it is a specific requirement of your homework exercise, I wouldn't do it. It is unnecessarily complicated and error prone - and only being allowed to use scanf() is a very artificial constraint. The requirement is to use the simplest technique can read the intended input, and recover sensibly if unintended characters are input.


    The problem with such a combined approach is that, if it gets in trouble, there is virtually no way your program can recover.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Averaging numbers in a while loop?
    By Chinnie15 in forum C Programming
    Replies: 3
    Last Post: 12-01-2011, 10:13 PM
  2. Array problem averaging numbers
    By Thedon in forum C Programming
    Replies: 6
    Last Post: 10-27-2011, 11:27 AM
  3. c# help needed with a mix of loop terminated sentinal
    By xbox221 in forum C# Programming
    Replies: 6
    Last Post: 01-10-2011, 09:23 PM
  4. averaging numbers?
    By rock4christ in forum C Programming
    Replies: 12
    Last Post: 09-09-2006, 06:38 PM
  5. averaging random numbers
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 10-27-2001, 03:48 PM