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

A simple C++ program that shows the functionality of an if-else statement.

Code Explanation

4Function header of the checkNumber() function. The function expects a return value of type string and as input parameter an integer variable.
5Creates a variable named result
7 – 8If the value of the variable num is greater than or equal to 0, the variable result is assigned the string “positive”
9 – 10Otherwise the value is set to “negative”
13Returns the variable result
17Creates a variable named num
19Prompts the user to enter a number
20The entered number is assigned to the variable num
22The function checkNumber() is now passed this value and the return value is output
#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;
Please enter a number: