A simple C++ program that shows the functionality of an if-else
statement.
Line | Description |
---|---|
4 | Function header of the checkNumber() function. The function expects a return value of type string and as input parameter an integer variable. |
5 | Creates a variable named result |
7 – 8 | If the value of the variable num is greater than or equal to 0, the variable result is assigned the string “positive” |
9 – 10 | Otherwise the value is set to “negative” |
13 | Returns the variable result |
17 | Creates a variable named num |
19 | Prompts the user to enter a number |
20 | The entered number is assigned to the variable num |
22 | The 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:
-3
negative