Average of user inputs (in a loop)

This is a discussion on Average of user inputs (in a loop) within the C Programming forums, part of the General Programming Boards category; My problem is I'm not sure how to get the program to identify each user input uniquely (in a loop). ...

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    33

    Average of user inputs (in a loop)

    My problem is I'm not sure how to get the program to identify each user input uniquely (in a loop). I suppose it would have been a lot easier if the users input, in this particular program,was fixed and not looped.

    I have to get the average of the scores entered in each loop. As you will notice, a negative integer is used to exit the loop. The negative integer is not included in the loop counting or the average.

    Code:
    #include <stdio.h>
    
    int main()
    {
    	int user_input = 1;
            int loop_count = -1;/*starts with -1 because the exit input (final input) is ignored*/
            float user_input_average;
    	
    	printf("The program calculates the average of scores you enter.\n");
    	printf("End with a negative integer.\n");
    	
    	do
    	{
    		printf("Enter score (3-10):");
    		user_input++;
    		loop_count++;
    		scanf("%d", &user_input);
    	}
    	while(user_input > -1);
    	
    	printf("You entered %d scores.\n", loop_count);
    	printf("Average score: %.2f\n", user_input_average);
    	
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    I dont think you want the "user_input++;" line, as its immediately overwritten in the "scanf" line.

    For an average you need two things: how many numbers to include, and the the sum of these numbers. You already have the "how many" part, represented by your "loop_count" variable. Note that if the first number entered by the user in the loop is <= -1, then it will report as loop_count = 2 numbers entered, when they really "entered" 0. So there's that bug.

    Next you need a running total. Just declare an "int", initialized to 0, and add each user input to this running total variable. Then do the division to store the average.

  3. #3
    Registered User
    Join Date
    Jan 2010
    Posts
    412
    Quote Originally Posted by nadroj View Post
    Note that if the first number entered by the user in the loop is <= -1, then it will report as loop_count = 2 numbers entered, when they really "entered" 0. So there's that bug.
    I think you missed the minus sign here
    Code:
    int loop_count = -1;

  4. #4
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    I think I did, good catch!

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,295
    Probably more significantly, you are not computing a value for user_input_average. An average of a set of values is normally computed by adding the values up and dividing by the number of values. So you need to keep track of the number of values input and the sum of the values entered.

    Just remember that integer division does not result in a float, so some conversion is necessary if you want a floating point result for the average.

    Also don't try to compute the average when there are zero inputs.....
    Right 98% of the time, and don't care about the other 3%.

  6. #6
    Registered User
    Join Date
    Feb 2010
    Posts
    33
    I managed to get it working with everyone's advise. Thanks

    Is there any unnecessary code within the program?

    Code:
    #include <stdio.h>
    
    int main()
    {
    	int user_input = 1;
        	int loop_count = -1;//starts with -1 because the exit input (final input) is ignored in the count
    	float sum = -1, average;
    	
    	printf("The program calculates the average of scores you enter.\n");
    	printf("End with a negative integer.\n");
    	
    	do
    	{
    		printf("Enter score (3-10):");
            	sum = sum + user_input;//used to determine the sum for the average
            	loop_count++;
    		scanf("%d", &user_input);
    	}
    	while(user_input > -1);
        	{
            	printf("You entered %d scores.\n", loop_count);
            	average = sum / loop_count;
            	printf("Average score: %.2f\n", average);
        	}
        	return 0;
    }

  7. #7
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    If on the very first iteration the user enters a number <= -1, then loop_count will be 0, and you will be dividing by zero. Also, your second pair of "{}"s doesn't do anything, so you could just as well remove them. Alternatively, I think as someone suggested, you could put the code after the loop into an "if" statement, and only calculate the average if the loop_count > 0.

  8. #8
    Registered User
    Join Date
    Feb 2010
    Posts
    57

    Thumbs up Re: Average of user inputs (in a loop)

    Is there any unnecessary code within the program?
    Yeah.

    Code:
    #include <stdio.h>
    
    int main()
    {
            int user_input = 1;
            int loop_count = -1;//starts with -1 because the exit input (final input) is ignored in the count
            float sum = -1, average;
    
            printf("The program calculates the average of scores you enter.\n");
            printf("End with a negative integer.\n");
    
            do
            {
                    printf("Enter score (3-10):");
                    sum = sum + user_input;//used to determine the sum for the average
                    loop_count++;
            }while(scanf("%d", &user_input)!=-1); // If you write do while statement like this it will be better while understanding your code.
    
            printf("\nYou entered %d scores.\n", loop_count);
            average = sum / loop_count;
            printf("Average score: %.2f\n", average);
            return 0;
    }
    And no need to check the condition like this,
    Code:
    while(user_input > -1);
    scanf will return when we give EOF(In unix ctrl+D) in stdin. so we can use that return value for thi condition.

    And you have put some unwanted braces after the do while loop.

    If you don't to store average, we can reduce another one statement
    Code:
    printf("Average score: %.2f\n",sum/loop_count);
    Last edited by sganesh; 03-07-2010 at 10:24 PM.

  9. #9
    Registered User
    Join Date
    Feb 2010
    Posts
    33
    Excellent... Those are the type of tips I was hoping for!!

    Thank you very much!

  10. #10
    Registered User
    Join Date
    Feb 2010
    Posts
    33
    Quote Originally Posted by sganesh View Post
    Yeah.
    }while(scanf("%d", &user_input)!=-1); // If you write do while statement like this it will be better while understanding your code.
    Just want to make sure since any negative integer could exit the loop - not just (-1).

    Shouldn't it be (or am I perhaps overlooking something):
    Code:
    }while(scanf("%d", &user_input)!<=-1); // If you write do while statement like this it will be better while understanding your code.
    Thanks
    Last edited by SilentPirate007; 03-08-2010 at 07:26 AM.

  11. #11
    Registered User
    Join Date
    Feb 2010
    Posts
    33
    I also tried to compile it for test purposes and it doesn't end the loop with any of the input I give.

  12. #12
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    If you want further help, post your complete (100% complete) code, as well as what your input and output is. Describe any other details we must know in order to help. If you leave any one of these out, it will only be hurting you because the help will be delayed until we get all of that information.

  13. #13
    Registered User
    Join Date
    Feb 2010
    Posts
    33
    Quote Originally Posted by nadroj View Post
    If you want further help, post your complete (100% complete) code, as well as what your input and output is. Describe any other details we must know in order to help. If you leave any one of these out, it will only be hurting you because the help will be delayed until we get all of that information.
    Well...The below code works just fine, but when I implement the advised code, that would just loop until I break it off...

    The code that works:

    Code:
    #include <stdio.h>
    
    int main()
    {
            int user_input = 1;
            int loop_count = -1;//starts with -1 because the exit input (final input) is ignored in the count
            float sum = -1;
    
            printf("\nThe program calculates the average of scores you enter.\n");
            printf("End with a negative integer.\n");
            printf("\n");
    
            do
            {
                    printf("Enter score (3-10): ");
                    sum += user_input;//used to determine the sum for the average
                    loop_count++;
                    scanf("%d", &user_input);
            }while(user_input >= 0);
    
            printf("\nYou entered %d scores.\n", loop_count);
            printf("Average score: %.2f\n", sum/loop_count);
            return 0;
    }
    When I put the scanf and while statement together, as advised, it doesn't work:

    Code:
    }while(scanf("%d", &user_input)!<=-1);
    or

    Code:
    }while(scanf("%d", &user_input)>=0);
    Oh and the output will just keep printing this line (no matter the user input - positive or negative):

    Code:
    printf("Enter score (3-10): ");
    The code should exit the loop when a negative integer is entered and it would print:

    Code:
    printf("\nYou entered %d scores.\n", loop_count);
    printf("Average score: %.2f\n", sum/loop_count);
    Last edited by SilentPirate007; 03-08-2010 at 04:36 PM. Reason: forgot some stuff

  14. #14
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    Code:
    }while(scanf("%d", &user_input)!<=-1);
    Does that even compile? If you are trying to negate the statement, don't put the "!" in the middle or whatever, put it at the start, like
    Code:
    }while( !(scanf("%d", &user_input)<=-1) );
    Also,
    Code:
    }while(scanf("%d", &user_input)>=0);
    will "almost always" be true. "scanf" returns the number of items read in, which I think will always be ">= 0", except in the "rare" case of an actual error. So this statement, for "practical" purposes will always be true. Since you're reading in 1 item, you maybe want to compare it to "==1".

    In my opinion, I'd choose to do it the way you initially were (reading in "user_input" then comparing that in your while loop condition). It's much more readable, and the extremely small space/cost efficiency gain you get from doing it the new way your trying to do is certainly not worth the added "complexity".

    Try and fix these things, then if you still have problems post your exact code you're running, so we simply have one piece of code to work on.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Average using for loop
    By funskoolz in forum C Programming
    Replies: 5
    Last Post: 03-27-2009, 05:59 AM
  2. Visual Studio Express / Windows SDK?
    By cyberfish in forum C++ Programming
    Replies: 23
    Last Post: 01-22-2009, 01:13 AM
  3. User input while loop is running
    By two31d in forum C++ Programming
    Replies: 7
    Last Post: 11-30-2005, 04:28 PM
  4. SSH Hacker Activity!! AAHHH!!
    By Kleid-0 in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 03-06-2005, 02:53 PM
  5. Replies: 6
    Last Post: 04-12-2002, 08:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21