Search code examples
c++new-operator

trying to make my first program to loop (c++)


im new to coding in general and was wondering how to make my little program loop, I can input 1 equation before it just doesn't do anything and was wondering how to fix that

#include<iostream>
using namespace std;
int main()
{
    for ( ; ; ) {
        cout << "INPUT 1 for div, INPUT 2 for mult THEN input 2 numbers";
        int sign;
        cin>>sign;
            if ( sign == 1 ) {
            int num1;
            cin>>num1;
            int num2;
            cin>>num2;
            cout << num1/num2;
        }
        else {
            int num1;
            cin>>num1;
            int num2;
            cin>>num2;
            cout << num1 * num2;
        }

        return 0;
    }
} 

Solution

  • Welcome to coding :)

    You have placed your return 0; statement inside your for-loop.

    Return 0; will make your main-function (and in this case your entire program) finish and exit immediately, no matter where it is encountered inside the function.

    You should move the return 0 statement outside the for loop like so:

    int main()
    {
    ...
        for ( ; ; ) {
            ...
                int num2;
                cin>>num2;
                cout << num1 * num2;
            }
    
        }
    
        return 0;
    }
    

    This way, the program should never hit the return statement and keep looping correctly.