C++ else if statement
Created By: chatGPT
In C++, the else if statement allows you to evaluate multiple conditions sequentially. It is particularly useful when you need to decide between several possible paths of execution based on different conditions. The if statement checks the first condition; if it's false, the program checks the next else if condition. If all previous conditions are false, the optional else block will execute.
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (number > 0) {
std::cout << "The number is positive.";
} else if (number < 0) {
std::cout << "The number is negative.";
} else {
std::cout << "The number is zero.";
}
return 0;
}
In this example, the program prompts the user to enter a number. Depending on the value of the entered number, it will print whether the number is positive, negative, or zero. Using the else if structure allows us to handle multiple possible outcomes without nested if statements.
if (condition1) {
// Code block for condition1
} else if (condition2) {
// Code block for condition2
} else {
// Code block if none of the above conditions are true
}