C++ If Else
if-else Statement in C++:
The if-else statement is used for decision-making in C++. It allows you to execute different blocks of code based on whether a certain condition is true or false. Here's the basic syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Here's a simple example to illustrate the use of if-else:
#include <iostream>
int main() {
int number;
// Get input from the user
std::cout << "Enter a number: ";
std::cin >> number;
// Check if the number is positive or negative
if (number > 0) {
std::cout << "The number is positive." << std::endl;
} else {
std::cout << "The number is non-positive." << std::endl;
}
return 0;
}
In this example, the program prompts the user to enter a number, and then it checks whether the entered number is positive or non-positive.
You can also extend if-else to include multiple conditions using else if:
#include <iostream>
int main() {
int number;
// Get input from the user
std::cout << "Enter a number: ";
std::cin >> number;
// Check the sign of the number
if (number > 0) {
std::cout << "The number is positive." << std::endl;
} else if (number < 0) {
std::cout << "The number is negative." << std::endl;
} else {
std::cout << "The number is zero." << std::endl;
}
return 0;
}
In this case, the program checks whether the entered number is positive, negative, or zero.
Remember the following points about if-else statements:
- The else part is optional. You can have an if statement without an else part.
- You can have multiple else if conditions to check for different cases.
- The conditions are evaluated in order, and the first true condition's block is executed. If none of the conditions is true, the else block (if present) is executed.
Understanding if-else statements is crucial for creating programs that make decisions based on user input, system conditions, or other variables.