Course Content
C++ Introduction
C++ Introduction
Conditional Statements
The if
construct in programming enables your program to make decisions and handle different scenarios.
It has two key components: a condition that evaluates to either true or false, and the actions or consequences that follow based on the outcome of that condition.
main
#include<iostream> // if (condition) // { // Actions to take if the condition is true // } int main() { int balance = 25; if (balance >= 13) { std::cout << "Balance is greater than 13, transaction is OKAY" << std::endl; } if (balance < 13) { std::cout << "Balance is less than 13, transaction is NOT OKAY" << std::endl; } }
The else
construct in programming is used in conjunction with an if
statement to define an alternative set of actions that should be executed when the condition in the if
statement is false.
main
#include<iostream> // if (condition) // { // Actions to take if the condition is true // } int main() { int balance = 25; if (balance >= 13) { std::cout << "Balance is greater than 13, transaction is OKAY" << std::endl; } else { std::cout << "Balance is less than 13, transaction is NOT OKAY" << std::endl; } }
You can have additional if...else
statements nested inside another if...else
block. This is known as nested if...else. This allows for more complex decision-making, where multiple conditions can be checked sequentially and different actions can be taken based on these conditions.
main
format_example
#include<iostream> int main() { int balance = 25; if (balance >= 13) // First condition: check if balance is greater than or equal to 13 { if (balance >= 20) // Nested condition: check if balance is greater than or equal to 20 { std::cout << "Balance is greater than or equal to 20, transaction is APPROVED" << std::endl; } else { std::cout << "Balance is between 13 and 19, transaction is OKAY" << std::endl; } } else { std::cout << "Balance is less than 13, transaction is NOT OKAY" << std::endl; } }
Note
If there is only one statement to execute within an
if
orelse
block, you can omit the curly braces. This can make the code more concise, but it also reduces clarity, especially in more complex conditions.
Thanks for your feedback!