entering specific amount of integers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gfanning23
    New Member
    • Mar 2016
    • 12

    entering specific amount of integers

    I am trying to write the code so it only enters a specific amount of numbers to average using a sentinel value.

    [CODE]#include <stdio.h>
    int main ()
    {
    /* variable definition: */
    int count, value, sum; avg;
    /* Initialize */
    count = 0;
    sum = 0; avg = 0.0;
    // Loop through to input values
    while(1){
    printf("Enter the number of integers you want to add and find average of: ");
    scanf("%d", &value);
    if (value == 10)
    break;
    sum = sum + value;
    count = count + 1; } else {
    printf("Value must be positive\n"); }
    }
    // Calculate avg. of two integers
    avg = sum/count;
    printf("average is %ld\n ", avg );
    return 0;
    }
    Last edited by gfanning23; Mar 24 '16, 12:45 PM. Reason: updated code
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Some comments.
    1. avg is an int so you cannot set it to 0.0.
    2. count = count + 1;} -- What block do you intend to terminate with "}"?
    3. else { printf("Value must be positive\n");} -- What if does this else go with?
    4. What happens if the very first number entered is 10? This will cause a divide-by-zero exception when avg is computed.
    5. print("average is %ld\n",avg); -- %ld is not the correct format specifier for an int like avg.


    By the way, you need "[/code]" at the end of the listing in order for your code snippet to be formatted like code. Code formatting would have provided line numbers that I could have used to identify which lines my comments pertain to.

    By the way, if you intend to disallow negative input numbers, then a negative value would make an excellent sentinel value to terminate data entry.

    Comment

    Working...