Skip to main content

Decision Making

C++ is a powerful and versatile programming language that allows you to make decisions within your code. This is accomplished through the use of control flow statements, which can change the order in which your code is executed based on certain conditions. In this tutorial, we'll cover the three main types of decision-making statements in C++: if, switch, and conditional (ternary) operator.

if Statement

The if statement is the simplest form of control flow statement. It executes a block of code if a specified condition is true.

Here's the syntax of an if statement:

if (condition) {
// code to be executed if the condition is true
}

For example:

int x = 10;
if (x > 5) {
cout << "x is greater than 5";
}

In this example, the if statement checks whether x is greater than 5. If the condition is true, it outputs "x is greater than 5".

if...else Statement

An if...else statement can execute different code blocks depending on whether a condition is true or false.

Here's the syntax of an if...else statement:

if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}

For example:

int x = 10;
if (x > 5) {
cout << "x is greater than 5";
} else {
cout << "x is not greater than 5";
}

switch Statement

The switch statement is used to perform different actions based on different conditions. It can be a more efficient alternative to if...else statements when dealing with many conditions.

Here's the syntax of a switch statement:

switch(expression) {
case constant1:
// code to be executed if expression is equal to constant1;
break;
case constant2:
// code to be executed if expression is equal to constant2;
break;
// you can have any number of case statements
default:
// code to be executed if expression doesn't match any constants
}

For example:

int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
// and so on for the rest of the week
default:
cout << "Invalid day";
}

Conditional (Ternary) Operator

The conditional (ternary) operator is a shorthand way of writing simple if...else statements. It's called "ternary" because it takes three operands: a condition, a result for true, and a result for false.

Here's the syntax of the ternary operator:

condition ? result_if_true : result_if_false

For example:

int x = 10;
string result = (x > 5) ? "x is greater than 5" : "x is not greater than 5";
cout << result;

In this tutorial, we've covered the basics of decision making in C++. Remember, the key to writing effective control flow statements is to clearly define your conditions and what should happen under each one. With practice, you'll be able to write complex programs that can make intelligent decisions.