C++ Code Example: check if a number is positive or negative

This code defines a function called checkNumber that takes an integer argument num and returns a string that indicates whether the number is positive or negative. The function starts by declaring a string variable called result that will store the result of the check. It then checks if the input number num is greater than or equal to zero using an if statement. If it is, the function sets result to “positive”, otherwise it sets it to “negative”. Finally, it returns the value of result.

The main function starts by declaring an integer variable num and then prompts the user to enter a number. It reads the input from the console using the cin function, and stores it in num. It then calls the checkNumber function with num as an argument, and prints the returned string to the console using the cout function.

#include <iostream>
using namespace std;

string checkNumber(int num) {
    string result;

    if (num >= 0) {
        result = "positive"; 
    } else {
        result = "negative";
    }

    return result;
}

int main() {
    int num;

    cout << "Please enter a number: " << endl;
    cin >> num;

    cout << checkNumber(num) << endl;
}
Output
Please enter a number: 
-3
negative