Decision Making in C++

Decision Making in C++

Decision making allows you to execute a particular block of code among several blocks, based on a condition. It's fundamental in programming as it enables your programs to act differently under different circumstances.

1. If Statement

The if statement executes a block of code if a specified condition is true.

Syntax:

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

Example:

int age = 20; if (age >= 18) { std::cout << "You are an adult." << std::endl; } 

2. If-Else Statement

The if-else statement provides an alternative block of code to be executed if the if condition is false.

Syntax:

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

Example:

int number = -5; if (number >= 0) { std::cout << "The number is positive." << std::endl; } else { std::cout << "The number is negative." << std::endl; } 

3. If-Else If-Else Statement

You can have multiple conditions using if-else if-else structure.

Syntax:

if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition2 is true } else { // code to be executed if both conditions are false } 

Example:

int number = 0; if (number > 0) { std::cout << "The number is positive." << std::endl; } else if (number < 0) { std::cout << "The number is negative." << std::endl; } else { std::cout << "The number is zero." << std::endl; } 

4. Switch Statement

The switch statement allows you to select one of many blocks of code to be executed.

Syntax:

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; ... default: // code to be executed if the expression doesn't match any constant; } 

Example:

int day = 4; switch (day) { case 1: std::cout << "Monday"; break; case 2: std::cout << "Tuesday"; break; case 3: std::cout << "Wednesday"; break; case 4: std::cout << "Thursday"; break; default: std::cout << "Another day"; } 

5. The Conditional (Ternary) Operator

It is a shorthand for the if-else statement.

Syntax:

variable = (condition) ? value_if_true : value_if_false; 

Example:

int age = 20; std::string status = (age >= 18) ? "Adult" : "Minor"; std::cout << "You are a " << status << "." << std::endl; 

6. Conclusion

Decision-making structures provide ways to control the flow of your programs based on conditions. Mastering these structures is essential for writing effective C++ programs. Make sure to practice different scenarios to get comfortable with each of them.


More Tags

boot postman-collection-runner prefix ssrs-2012 dispatchevent crt flutter-plugin public-key android-livedata keypress

More Programming Guides

Other Guides

More Programming Examples