While loop won't run

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • GraxGunz
    New Member
    • Jul 2011
    • 13

    While loop won't run

    (cpp newbie here)
    my program have to show the number of positive numbers, negative numbers, the sum of these numbers, and the average of these numbers, and the program exit when the input is 0

    wanna ask here what's wring with my code? y me while loop can't run? did i have to used do while loop?
    Code:
    #include <iostream>
    #include <conio.h>
    
    using namespace std;
    
    int main()
    {
        
        int num = 0;
        int count = 0;
        int positive = 0;
        int negative = 0;
        int sum = 0;
        float average = 0;
        
        
        cout << "Enter an int value, the program exit when the input is 0:\n>> ";
        cin >> num;
            
    
        while( num != 0)
        {
         count++;
        
         if (num > 0)
           positive += 1;
        
          else if (num < 0)
            negative += 1;
        
         sum += num;
        
        }
        
        
        average = static_cast<float>(sum) / static_cast<float>(count);
        cout << "The number of positive is " << positive << endl;
        cout << "The number of negative is " << negative << endl;
        cout << "The total is " << sum << endl;
        cout << "The average is " << average << endl;
        
        getch();
        return 0;
    }
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    It's running. In fact, it's an infinite loop. If the user enters any non-zero number, it will enter an infinite loop because the num variable never changes.

    Comment

    • GraxGunz
      New Member
      • Jul 2011
      • 13

      #3
      sorry, i'm not so understand bout this.... how can i stop the infinite loop?

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        Your loop needs to ask for a new num during each iteration. Otherwise the loop never evaluates to anything else than the initial value.

        Comment

        • GraxGunz
          New Member
          • Jul 2011
          • 13

          #5
          now i know it, i just hv to add cin >> num; in my loop! problem solved! thx a lot!

          Comment

          Working...