Thread: sentinel value or if statement help

  1. #1
    Registered User
    Join Date
    Feb 2018
    Posts
    2

    sentinel value or if statement help

    Below is my code:
    I'm brand new to C code.

    I am able to stop the code from calculating the average after "12345" is entered but the code is calculating "12345: and not breaking the loop.

    I also want the user to be able to enter as many numbers as they want until they enter "12345"

    Do I need to remove the while statement with the counter?

    Code:
    #include <stdio.h>
    int main ()
    {
    /* variable definition: */
    int count, value,sum;
    double avg;
    /* Initialize */
    count = 0;
    sum = 0;
    avg = 0.0;
    // Loop through to input values
    while (count < 20)
    {
    
    
    printf("Enter as many positive Integers as you like"
    " When finished simply type 12345 to calculate the average  \n");
    scanf("%d",&value);
    if (value >= 0) {
        sum = sum + value;
       count = count + 1;
       if (value == 12345)
       break;
    }
    else
    {
         printf("Value must be positive\n");
    }
    }
    // Calculate avg. Need to type cast since two integers will yield an integer
    avg = (double) sum/count;
    printf("average is %lf\n " , avg );
    return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,660
    Perhaps you should compare first, then calculate.
    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.

  3. #3
    Registered User
    Join Date
    Feb 2018
    Posts
    2
    Quote Originally Posted by Salem View Post
    Perhaps you should compare first, then calculate.


    Touché
    Ha

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with sentinel value
    By saahmed in forum C++ Programming
    Replies: 8
    Last Post: 02-15-2006, 06:22 PM
  2. SENTINEL question
    By codeHer1 in forum C Programming
    Replies: 2
    Last Post: 03-24-2005, 09:34 AM
  3. rb tree Sentinel NIL
    By dinjas in forum C Programming
    Replies: 2
    Last Post: 03-06-2005, 12:28 AM
  4. Sentinel Value and numbering
    By fjf314 in forum C++ Programming
    Replies: 10
    Last Post: 01-09-2004, 09:04 PM
  5. sentinel
    By oscuro in forum C++ Programming
    Replies: 1
    Last Post: 03-12-2002, 05:48 PM

Tags for this Thread