Introduction
An if-else statement helps your program make choices. It runs different code depending on a condition.
An if-else statement helps your program make choices. It runs different code depending on a condition.
if (condition) { // code to run if condition is true } else { // code to run if condition is false }
condition is a test that is either true or false.if part or the else part.number is greater than zero.int number = 10; if (number > 0) { // number is positive } else { // number is zero or negative }
bool isRaining = false; if (isRaining) { // take umbrella } else { // no umbrella needed }
This program asks for your age and tells you if you are an adult or a minor using an if-else statement.
#include <iostream> int main() { int age; std::cout << "Enter your age: "; std::cin >> age; if (age >= 18) { std::cout << "You are an adult.\n"; } else { std::cout << "You are a minor.\n"; } return 0; }
Make sure the condition inside if uses comparison operators like ==, >, <.
Use braces { } even for one line inside if or else to avoid mistakes.
If-else lets your program choose between two paths.
The if block runs when the condition is true.
The else block runs when the condition is false.
if-else statement do in C++?int x = 5;
if (x < 3) {
cout << "Less";
} else {
cout << "More or equal";
}int n = 10;
if n > 5 {
cout << "Big";
} else {
cout << "Small";
}Pass the test and this pattern moves unknown