C++ – Stop Code in C++

c

How do you stop the code from running in C++? I have the code

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    int total, sub, subc;
    cout << "What number would you like to start with? ";
    cin >> total;
        cout << "Enter in a number, 1 or 2, to subtract";
    cin >> sub;
    if (sub == 1) {
        total--;
        subc++;
        cout << "You subtracted one";
    }
    else {
        total = total - 2;
        subc++;
    }
    if (sub <= 0)
        cout << "YAY!";
}

and i want to insert a thing that just stops the code and exits right after cout << "YAY!"
how do i do that???

Best Answer

A return statement will end the main function and therefore the program:

return 0;

ETA: Though as @Mysticial notes, this program will indeed end right after the cout << "YAY!" line.

ETA: If you are in fact working within a while loop, the best way to leave the loop would be to use a break statement:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    int total, sub, subc;
    cout << "What number would you like to start with? ";
    cin >> total;
    while (1) {
            cout << "Enter in a number, 1 or 2, to subtract";
        cin >> sub;
        if (sub == 1) {
            total--;
            subc++;
            cout << "You subtracted one";
        }
        else {
            total = total - 2;
            subc++;
        }
        if (sub <= 0) {
            cout << "YAY!";
            break;
        }
    }
}
Related Topic