Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Conditional Statements | Introduction to Program Flow
C++ Introduction
course content

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Introduction to Operators
3. Variables and Data Types
4. Introduction to Program Flow
5. Introduction to Functions

bookConditional 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.

cpp

main

copy
1234567891011121314151617181920
#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.

cpp

main

copy
1234567891011121314151617181920
#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.

cpp

main

cpp

format_example

copy
12345678910111213141516171819202122
#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 or else block, you can omit the curly braces. This can make the code more concise, but it also reduces clarity, especially in more complex conditions.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt