C++ Basic if-else statements
When making judgments in C++, the if-else statement is employed. The code inside the if block is run if the condition is true,otherwise, the code inside the else block is executed.
Basic syntax of if-else statement:
if (condition) {
// code to be executed if condition is true
}
else {
// code to be executed if condition is false
}
Here’s an example of the if-else statement:
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num > 0) {
cout << num << " is positive" << endl;
}
else if (num < 0) {
cout << num << " is negative" << endl;
}
else {
cout << num << " is zero" << endl;
}
return 0;
}
Output:
Enter a number: 5
5 is positive
This example prompts the user to enter a number that is then used by cin to save it in the num variable. The if-else statement uses the relational operators >,, and == to determine if the value of num is larger than 0, less than 0, or equal to 0, and then uses cout to output the appropriate message to the console. The message “is positive” is printed if num is larger than 0, “is negative” is printed if num is less than 0, and “is zero” is printed if num is exactly 0.