Thread: Loop structuring problem

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    5

    Loop structuring problem

    I am having a problem with my loop structure code:

    Code:
    #include <iostream>
    using namespace std;
    
    void main( )
    {
    cout << "Value 0 will end process!" << endl;
    	double Average = 0.00;
    	int Sum = 0;
    int Counter = 0;
    int temp;
    do
    {
    	cout << "Enter Temperature:";
    	cin >> temp;
    	Sum += temp;
    	Counter++;
    }
    while(temp != 0);
    	
    Average = Sum / Counter;
    cout << "Average Temperature = " << Average << endl;
    }
    
    /* Captured output
    
    Enter Temperature:78
    Enter Temperature:90
    Enter Temperature:85
    Enter Temperature:80
    Enter Temperature:87
    Enter Temperature:83
    Enter Temperature:75
    Enter Temperature:90
    Enter Temperature:86
    Enter Temperature:70
    Enter Temperature:0
    Average Temperature = 74
    Press any key to continue . . .
    
    */
    I have a trip value of 0 set to the code so it will end the loop. What I am trying to figure out is how to dismiss the 0 from the calculation of the average in the loop so it will only calculate however many entries there are until you end the loop with a 0. Anyone got an idea?
    Last edited by steeno321; 12-04-2010 at 09:04 PM.

  2. #2
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    463
    You could put into the body of the loop:
    Code:
    if(temp == 0) break;
    However, it's not good to use "0" as a terminating condition though, because the temperature of '0 degree' is a valid. You want to think of different terminating condition.
    BTW, Average is not calculated correctly. Both Sum and Counter are type int. The value of Average will be the truncated result of Sum/Counter.
    Last edited by nimitzhunter; 12-04-2010 at 09:33 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple loop problem I cant seem to solve
    By LightYear in forum C Programming
    Replies: 8
    Last Post: 03-21-2010, 06:59 PM
  2. Problem with infinite loop in signal handler
    By semun in forum C Programming
    Replies: 6
    Last Post: 07-22-2009, 01:15 PM
  3. Addition problem in loop
    By murjax in forum C Programming
    Replies: 3
    Last Post: 07-01-2009, 06:29 PM
  4. validation problem in a loop (newbie question)
    By Aisthesis in forum C++ Programming
    Replies: 11
    Last Post: 05-10-2009, 10:47 PM
  5. For Loop Problem
    By xp5 in forum C Programming
    Replies: 10
    Last Post: 09-05-2007, 04:37 PM