Thread: What did I do wrong? Need someone to review my code for an assignment

  1. #1
    Registered User
    Join Date
    Jul 2013
    Posts
    29

    What did I do wrong? Need someone to review my code for an assignment

    Write a C program that prompts for a variable number of integers, adds them up, averages them, and prints out the average.
    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.


    I got a 85 but I feel I accomplished the task and should've been scored higher. The instructors feedback was Use int num and compare it with 999 to stop.
    That way, two scanf() statements are not required.

    insert
    Code:
    #include <stdio.h>
    
    
    int main()
    {
        
        float average, num,  total;
        int count, stop=0;
    
    
        count=0;
        total=0.0;
    
    
        
        while (stop != 999)
    
    
        {
            
            printf("\nenter a number ");
            scanf("%f", &num);
            count++;
            total += num;
            
            
            printf("the total is now %.f\n", total);
            printf("\nenter 999 to calculate the avg or 0 to continue ");
            
            scanf("%d", &stop);
            
            
            
        }
            
            
            average =total / count;
            printf("The average of all the numbers is: %.f", average);
                return 0;
            
    
    
    }
    Last edited by dmar0123; 07-18-2013 at 08:36 AM.

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Well, you did a good attempt, but you did not meet the requirements. You should check to see if num is 999 and if so, use the keyword break (I suggest) to break the loop (or check for it in the while condition) and then do the average and printing. You should not use the variable stop, nor using a second scanf.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  3. #3
    Registered User
    Join Date
    Jul 2013
    Posts
    29
    Thanks for the reply. I used the stop variable as the sentinel. Did I use it incorrectly?

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by dmar0123 View Post
    Thanks for the reply. I used the stop variable as the sentinel. Did I use it incorrectly?
    Yes. Reread what your instructor told you. Use num and compare it with 999 (the sentinel value).

    "stop" is completely unnecessary, and the scanf() for stop is redundant. There should be no second scanf() inside the while loop.

  5. #5
    Ticked and off
    Join Date
    Oct 2011
    Location
    La-la land
    Posts
    1,728
    Quote Originally Posted by dmar0123 View Post
    I got a 85 but I feel I accomplished the task and should've been scored higher.
    Your program prompts the user for sentinel/non-sentinel, after each value. It means that the instructor wanted a program where the user could input say
    Code:
    150
    300
    450
    200
    999
    and get the average, 275.

    Your program requires input
    Code:
    150
    0
    300
    0
    450
    0
    200
    999
    with any integer except 999 instead of 0 above.

    Do you see how important the difference is?

    Here's how I'd recommend to solve the exercise:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        double sum = 0.0; /* Sum total of inputs */
        long count = 0L;  /* Number of inputs */
        long value;
    
        /* Loop as long as there is an integer in standard input: */
        while (scanf("%ld", &value) == 1) {
    
            /* 999 is also an end-of-input sentinel. */
            if (value == 999L)
                break;
    
            /* Add value to sum. */
            sum += (double)value;
            count++;
        }
    
        if (count > 0L) {
            printf("%g (%ld integers)\n", sum / (double)count, count);
        } else {
            printf("No integers in input.\n");
        }
    
        return 0;
    }
    Mine uses double-precision floating point numbers, and the long type for the integer inputs, for maximum precision and input range, but otherwise the logic is the same. (Longs are just like ints, except on many architectures, can describe a much larger range of integers. The L at end of numeric constants means the constant is of long type, not an int.)

    The first critical point is the scanf() call. You must check its return value. It tells you how many assignments it does. If it returns less than 1, it means it cannot parse the input, or that there is no more input -- and most importantly, the value is not modified, and the "bad" input is not consumed! (This means that if you supply say "foo" to your program, it will get stuck in an endless loop, because instead of recognizing "foo", it thinks it re-read the previous number. Over and over.)

    After an integer has been parsed from input, you need to check if it is the sentinel value, 999. The L at end means it is a long constant.

    If there were a lot of numbers to average, it is possible that even a long would overflow. That's why I used a double-precision floating point type to store the sum. The cast, (double), is not strictly necessary as the compiler does it implicitly in this case, but I put it there for illustration. (The same applies to the cast in the printf statement, too.)

    In case there were no integers in the input (say, 999 was the first number scanned), this program checks count for zero, to avoid the division by zero error.

    This program also accepts inputs like "150 300 450 200 *", or "150 300 450 200 end". Anything that does not look like an integer to scanf() will stop the while loop. (In your case, the program will loop forever, adding the previous value to the sum.)

    I'd say 85 is pretty fair. I'd personally award less points, mostly due to not checking scanf() return value -- but I'm quite strict about handling unexpected input.

    (Handling unexpected input is, in my opinion, a very important thing, and sadly quite often overlooked. A lot of common bugs -- buffer overruns, unsanitized inputs to programs -- are due to not being paranoid enough about the quality of the input supplied to the program. It is something you must bake in to your logic, not something you can easily add afterwards.)

  6. #6
    Registered User
    Join Date
    Jul 2013
    Posts
    29
    This is what I could come up with. What do you guys think does it solve the question?

    Code:
    #include <stdio.h>
    
    
    int main()
    {
        
        float average,total, num;
        int count ;
        
        
        
        count=0;
        total=0;
    
    
        
        do
    
    
        {
            
            printf("\nenter a number ");
            scanf("%f", &num);
            if (num == 999)
            break;
            count++;
            total += num;
    
    
            
            
            
            printf("the total is now %.f\n", total);
            
            
            
            
            
            
        }
        while(1);
            
            
            
            average =total / count;
            printf("The average of all the numbers is: %.f", average);
                return 0;
            
    
    
    }
    Last edited by dmar0123; 07-18-2013 at 10:32 AM.

  7. #7
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Well, this seems ok, but the num!= 999 condition seems to be redundant. You could use
    Code:
    while(1)
    or even better, stick to the while loop you had in your first attempt, and have as condition the sum != 999
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  8. #8
    Registered User
    Join Date
    Jul 2013
    Posts
    29
    Yea I know its redundant didn't know what to place by while(). Where would I place the condition sum != 999 and do I declare sum=0; ?

  9. #9
    Registered User
    Join Date
    Feb 2013
    Location
    Sweden
    Posts
    89
    Quote Originally Posted by dmar0123 View Post
    This is what I could come up with. What do you guys think does it solve the question?

    Code:
    #include <stdio.h>
    
    
    int main()
    {
        
        float average,total, num;
        int count ;
        
        
        
        count=0;
        total=0;
    
    
        
        do
    
    
        {
            
            printf("\nenter a number ");
            scanf("%f", &num);
            if (num == 999)
            break;
            count++;
            total += num;
    
    
            
            
            
            printf("the total is now %.f\n", total);
            
            
            
            
            
            
        }
        while(num != 999);
            
            
            
            average =total / count;
            printf("The average of all the numbers is: %.f", average);
                return 0;
            
    
    
    }
    I just took a quick look. My first spontaneous thought is that ”while(num != 999);” is redundant, since ”if(num == 999) break;” is already inside the loop.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,403
    Quote Originally Posted by dmar0123
    Yea I know its redundant didn't know what to place by while(). Where would I place the condition sum != 999 and do I declare sum=0; ?
    It depends. For example, have you learnt how to define your own functions? One option is to move a certain part of the code for the loop into a function, then call the function to determine when to end the do while loop.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Jul 2013
    Posts
    29
    @ gura Yes I changed the while(num != 999); to while(1); But besides that
    Last edited by dmar0123; 07-18-2013 at 10:36 AM.

  12. #12
    Registered User
    Join Date
    Jul 2013
    Posts
    29
    Actually defining my own functions is in the next chapter I tackle that assignment tonight. So haven't learned it yet.
    Last edited by dmar0123; 07-18-2013 at 10:38 AM.

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,403
    Quote Originally Posted by dmar0123
    I changed the while(num != 999); to while(1);
    Don't do that. Rather, change the entire do while loop into a while loop.

    Quote Originally Posted by dmar0123
    Actually defining my own functions is in the next chapter
    Okay, then don't worry about that for now.

    Incidentally, you should remove all those extra blank lines and indent your code consistently, e.g.,
    Code:
    #include <stdio.h>
    
    
    int main()
    {
        float average, total, num;
        int count;
    
        count = 0;
        total = 0;
    
        while (1)
        {
            printf("\nenter a number ");
            scanf("%f", &num);
            if (num == 999)
                break;
            count++;
            total += num;
    
            printf("the total is now %.f\n", total);
        }
    
        average = total / count;
        printf("The average of all the numbers is: %.f\n", average);
        return 0;
    }
    Also, what happens if the user enters 999 as the very first input?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User
    Join Date
    Jul 2013
    Posts
    29
    Also, what happens if the user enters 999 as the very first input?[/QUOTE]

    It outputs a -1 because theres no integers fed into total variable. So if 999 is inputted in the very beginning it exits the loop but still tries to find the average. What is the real difference of a do while verses a while? My understanding of the concept is Do (the loop) until the while is proved false. The While loop will only run as long as it remains true.
    Last edited by dmar0123; 07-18-2013 at 10:56 AM.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,403
    Quote Originally Posted by dmar0123
    It outputs a -1 because theres no integers fed into total variable. So if 999 is inputted in the very beginning it exits the loop but still tries to find the average.
    At that point, count is 0, so you have a division by 0 error. The -1 is just a symptom of that. You should check for this and handle the case accordingly.

    Quote Originally Posted by dmar0123
    What is the real difference of a do while verses a while? My understanding of the concept is Do (the loop) until the while is proved false. The While loop will only run as long as it remains true.
    The do while loop will run at least once. Running until it is "proved false" and running "as long as it remains true" are two different ways of saying the same thing, but notice that for the while loop, the test of the condition comes first, whereas for the do while loop it comes at the end of the iteration.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review please
    By Richardcavell in forum C Programming
    Replies: 3
    Last Post: 05-13-2011, 11:01 AM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. code review
    By hamsteroid in forum C Programming
    Replies: 6
    Last Post: 04-04-2007, 12:23 PM
  4. Review my finished assignment
    By damonbrinkley in forum C Programming
    Replies: 11
    Last Post: 06-24-2003, 07:15 AM
  5. Code review please
    By Brighteyes in forum C Programming
    Replies: 9
    Last Post: 03-29-2003, 06:28 PM