C++ else statement
Created By: chatGPT
In C++, the
else
statement is used to execute a block of code when the condition specified in the if
statement evaluates to false. This allows for conditional execution of different code paths based on whether a condition is met or not.if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
You can also use
else if
to check multiple conditions. This maintains a clear flow of logic and helps avoid deep nesting of if
statements.if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code when both conditions are false
}
Here’s an example demonstrating the use of an
In this program, if the entered else
statement in a simple program that checks the age to determine whether someone is eligible to vote.#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
if (age >= 18) {
std::cout << "You are eligible to vote.";
} else {
std::cout << "You are not eligible to vote.";
}
return 0;
}
age
is 18 or older, the program outputs that the user is eligible to vote. If the age is less than 18, the else block executes and informs the user that they are not eligible.