Search code examples
loopsinfinite

Why am I getting an infinite loop?


My output prints positive or negative repeatedly. Why am I getting an infinite loop? I used the following:

include iostream 
using namespace std; 

int main()
{
    int num;

    cout<<"enter number"<<endl;
    cin>>num;

    while(num!=0)
    {
        if(num>0)
            cout<<"positive"<<endl;
        else
            cout<<"negative"<<endl;
    }

    return 0;
}

Solution

  • Based on madflame991's answere here is an improved version :)

    include iostream 
    using namespace std; 
    
    int main()
    {
        int num;
    
        do
        {
            cout<<"enter number"<<endl;
            cin>>num;
    
            if(num>0)
                cout<<"positive"<<endl;
            else
                cout<<"negative"<<endl;
        }while(num!=0);
    
        return 0;
    }