Progress4 of 20 topics

20% complete

Control Flow in C++

Control flow statements allow you to control the execution path of your program based on conditions, enabling repetition of code blocks, and making decisions during runtime. C++ provides several control flow structures that are essential for creating dynamic and responsive programs.

What You'll Learn

  • How to use conditional statements (if, else if, else)
  • How to implement switch statements for multiple conditions
  • How to create loops for repetitive tasks (for, while, do-while)
  • How to use jump statements to control program flow
  • Best practices for writing clean and efficient control flow

Conditional Statements

Conditional statements allow you to execute different blocks of code based on whether a condition evaluates to true or false. C++ provides several ways to implement conditional logic.

if Statement

The most basic form of a conditional statement is the if statement, which executes a block of code only if the specified condition is true.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int number = 10;
6
7 if (number > 0) {
8 cout << "The number is positive." << endl;
9 }
10
11 return 0;
12}

if-else Statement

The if-else statement allows you to execute one block of code if the condition is true, and another block if the condition is false.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int number = -5;
6
7 if (number >= 0) {
8 cout << "The number is positive or zero." << endl;
9 } else {
10 cout << "The number is negative." << endl;
11 }
12
13 return 0;
14}

if-else if-else Statement

When you need to check multiple conditions, you can use the if-else if-else statement chain.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int score = 85;
6
7 if (score >= 90) {
8 cout << "Grade: A" << endl;
9 } else if (score >= 80) {
10 cout << "Grade: B" << endl;
11 } else if (score >= 70) {
12 cout << "Grade: C" << endl;
13 } else if (score >= 60) {
14 cout << "Grade: D" << endl;
15 } else {
16 cout << "Grade: F" << endl;
17 }
18
19 return 0;
20}

Nested if Statements

You can also nest if statements inside other if or else blocks to create more complex conditions.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int age = 25;
6 bool hasLicense = true;
7
8 if (age >= 18) {
9 cout << "Person is an adult." << endl;
10
11 if (hasLicense) {
12 cout << "Person can drive." << endl;
13 } else {
14 cout << "Person cannot drive without a license." << endl;
15 }
16 } else {
17 cout << "Person is a minor and cannot drive." << endl;
18 }
19
20 return 0;
21}

Conditional (Ternary) Operator

The conditional operator ? : provides a shorthand way to write simple if-else statements.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int number = 10;
6
7 // Ternary operator syntax: condition ? expression_if_true : expression_if_false
8 string result = (number % 2 == 0) ? "even" : "odd";
9
10 cout << "The number is " << result << "." << endl;
11
12 // Equivalent if-else statement
13 if (number % 2 == 0) {
14 result = "even";
15 } else {
16 result = "odd";
17 }
18
19 return 0;
20}

Switch Statement

The switch statement provides a clean way to execute different code blocks based on the value of a variable. It's particularly useful when you have multiple conditions based on a single variable.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 char grade = 'B';
6
7 switch (grade) {
8 case 'A':
9 cout << "Excellent!" << endl;
10 break;
11 case 'B':
12 cout << "Good job!" << endl;
13 break;
14 case 'C':
15 cout << "Satisfactory." << endl;
16 break;
17 case 'D':
18 cout << "Needs improvement." << endl;
19 break;
20 case 'F':
21 cout << "Failed." << endl;
22 break;
23 default:
24 cout << "Invalid grade." << endl;
25 }
26
27 return 0;
28}

Important Note about break

The break statement is crucial in a switch statement. Without it, execution "falls through" to the next case. This can occasionally be useful, but is usually not what you want. Always include break unless you specifically need fall-through behavior.

Loops in C++

Loops allow you to execute a block of code repeatedly. C++ provides several types of loops to suit different programming needs.

for Loop

The for loop is ideal when you know in advance how many times you want to execute a block of code.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Basic for loop
6 for (int i = 1; i <= 5; i++) {
7 cout << i << " ";
8 }
9 cout << endl;
10
11 // Output: 1 2 3 4 5
12
13 // for loop with different increments
14 for (int i = 0; i <= 10; i += 2) {
15 cout << i << " ";
16 }
17 cout << endl;
18
19 // Output: 0 2 4 6 8 10
20
21 // Countdown with for loop
22 for (int i = 5; i > 0; i--) {
23 cout << i << " ";
24 }
25 cout << endl;
26
27 // Output: 5 4 3 2 1
28
29 return 0;
30}

Range-based for Loop (C++11)

Introduced in C++11, the range-based for loop provides a simpler syntax for iterating over elements in a collection.

cpp
1#include <iostream>
2#include <vector>
3using namespace std;
4
5int main() {
6 vector<int> numbers = {1, 2, 3, 4, 5};
7
8 // Range-based for loop
9 for (int num : numbers) {
10 cout << num << " ";
11 }
12 cout << endl;
13
14 // Output: 1 2 3 4 5
15
16 // Range-based for loop with auto keyword
17 for (auto num : numbers) {
18 cout << num * 2 << " ";
19 }
20 cout << endl;
21
22 // Output: 2 4 6 8 10
23
24 // Using references to modify elements
25 for (auto& num : numbers) {
26 num *= 3;
27 }
28
29 // Print modified values
30 for (auto num : numbers) {
31 cout << num << " ";
32 }
33 cout << endl;
34
35 // Output: 3 6 9 12 15
36
37 return 0;
38}

while Loop

The while loop executes a block of code as long as a specified condition is true. It checks the condition before executing the loop body.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int count = 1;
6
7 while (count <= 5) {
8 cout << count << " ";
9 count++;
10 }
11 cout << endl;
12
13 // Output: 1 2 3 4 5
14
15 // Example with user input
16 int number;
17 cout << "Enter a positive number: ";
18 cin >> number;
19
20 while (number <= 0) {
21 cout << "That's not a positive number. Try again: ";
22 cin >> number;
23 }
24
25 cout << "You entered: " << number << endl;
26
27 return 0;
28}

do-while Loop

The do-while loop is similar to the while loop, but it checks the condition after executing the loop body, ensuring that the loop body executes at least once.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int count = 1;
6
7 do {
8 cout << count << " ";
9 count++;
10 } while (count <= 5);
11 cout << endl;
12
13 // Output: 1 2 3 4 5
14
15 // Example where the condition is false initially
16 int x = 10;
17
18 do {
19 cout << "This will execute once even though the condition is false." << endl;
20 } while (x < 5);
21
22 // Example with user input validation
23 int number;
24
25 do {
26 cout << "Enter a number between 1 and 10: ";
27 cin >> number;
28 } while (number < 1 || number > 10);
29
30 cout << "You entered a valid number: " << number << endl;
31
32 return 0;
33}

while vs. do-while

while loop: Checks the condition first, then executes the body. If the condition is initially false, the loop body never executes.

do-while loop: Executes the body first, then checks the condition. The loop body always executes at least once, even if the condition is initially false.

When to Use Each Loop

  • for: When you know the exact number of iterations
  • range-based for: When working with collections
  • while: When you want to continue based on a condition
  • do-while: When you need to execute at least once

Jump Statements

Jump statements alter the normal flow of program execution. C++ provides several jump statements to control the flow within loops and other control structures.

break Statement

The break statement terminates the nearest enclosing loop or switch statement.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Using break in a for loop
6 for (int i = 1; i <= 10; i++) {
7 if (i == 6) {
8 break; // Exit the loop when i equals 6
9 }
10 cout << i << " ";
11 }
12 cout << endl;
13
14 // Output: 1 2 3 4 5
15
16 // Using break in a while loop
17 int count = 1;
18 while (count <= 10) {
19 if (count % 7 == 0) {
20 break; // Exit when count is divisible by 7
21 }
22 cout << count << " ";
23 count++;
24 }
25 cout << endl;
26
27 // Output: 1 2 3 4 5 6
28
29 return 0;
30}

continue Statement

The continue statement skips the rest of the current iteration and proceeds to the next iteration of the loop.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Using continue in a for loop to skip even numbers
6 for (int i = 1; i <= 10; i++) {
7 if (i % 2 == 0) {
8 continue; // Skip even numbers
9 }
10 cout << i << " ";
11 }
12 cout << endl;
13
14 // Output: 1 3 5 7 9
15
16 // Using continue in a while loop
17 int count = 0;
18 while (count < 10) {
19 count++;
20 if (count % 3 == 0) {
21 continue; // Skip numbers divisible by 3
22 }
23 cout << count << " ";
24 }
25 cout << endl;
26
27 // Output: 1 2 4 5 7 8 10
28
29 return 0;
30}

goto Statement

The goto statement allows an unconditional jump to a labeled statement within the same function. While it exists in C++, it's generally discouraged in modern programming due to the difficulty in understanding and maintaining code that uses it.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Using goto (generally not recommended)
6 int i = 1;
7
8start: // Label
9 if (i <= 5) {
10 cout << i << " ";
11 i++;
12 goto start; // Jump to the label
13 }
14 cout << endl;
15
16 // Output: 1 2 3 4 5
17
18 return 0;
19}

Warning about goto

The goto statement is often considered harmful and can lead to "spaghetti code" that is difficult to follow and maintain. In modern C++ programming, it's best to use structured control flow statements (if, for, while, switch) instead of goto.

return Statement

The return statement exits from the current function and returns control to the calling function. It can also return a value if the function is not of void type.

cpp
1#include <iostream>
2using namespace std;
3
4// Function that returns a value
5int square(int num) {
6 return num * num; // Exit the function and return the squared value
7}
8
9// Function with early return
10bool isEven(int num) {
11 if (num % 2 == 0) {
12 return true; // Exit early if the number is even
13 }
14
15 // This part only executes if the number is odd
16 return false;
17}
18
19int main() {
20 cout << "Square of 5 is: " << square(5) << endl;
21
22 int number = 7;
23 if (isEven(number)) {
24 cout << number << " is even." << endl;
25 } else {
26 cout << number << " is odd." << endl;
27 }
28
29 return 0; // Exit main function
30}

Nested Loops

You can nest loops inside other loops to create more complex patterns and algorithms.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Nested for loops to create a multiplication table
6 for (int i = 1; i <= 5; i++) {
7 for (int j = 1; j <= 5; j++) {
8 cout << i * j << " ";
9 }
10 cout << endl;
11 }
12
13 // Nested loops for pattern printing
14 cout << "
15Pattern:" << endl;
16 for (int i = 1; i <= 5; i++) {
17 for (int j = 1; j <= i; j++) {
18 cout << "* ";
19 }
20 cout << endl;
21 }
22
23 return 0;
24}

Infinite Loops

Infinite loops continue indefinitely unless terminated by a break statement, return statement, or some other mechanism like an exit() function call. While they can be useful in certain scenarios, they should be used with caution to avoid program crashes.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Infinite for loop
6 // for (;;) {
7 // cout << "This will run forever..." << endl;
8 // }
9
10 // Infinite while loop
11 // while (true) {
12 // cout << "This will also run forever..." << endl;
13 // }
14
15 // Controlled infinite loop with a break condition
16 int count = 0;
17 while (true) {
18 cout << "Iteration: " << count << endl;
19 count++;
20
21 if (count >= 5) {
22 cout << "Breaking out of the infinite loop." << endl;
23 break;
24 }
25 }
26
27 return 0;
28}

Best Practices for Control Flow

  • Keep conditions simple and readable
  • Avoid deeply nested if statements when possible
  • Use switch statements for multiple conditions on the same variable
  • Prefer for loops when the number of iterations is known
  • Use while loops when you need to continue based on a condition
  • Avoid goto statements in favor of structured control flow
  • Always include breaks in switch statements unless you deliberately want fall-through behavior
  • Be cautious with infinite loops, ensuring there's a way to terminate them

Summary

In this tutorial, you've learned:

  • How to use if, if-else, and if-else if-else statements for decision making
  • How to implement switch statements for multiple conditions
  • How to create and control loops using for, while, and do-while
  • How to use range-based for loops for collections (C++11)
  • How to use jump statements like break, continue, and return
  • How to work with nested loops for complex patterns
  • Best practices for writing clear and efficient control flow in C++

Control flow is a fundamental concept in programming that allows you to create dynamic, responsive applications. Understanding these concepts is essential for becoming proficient in C++ programming.

Practice Exercise

Try implementing a simple calculator program in C++ that uses a switch statement to perform different operations (addition, subtraction, multiplication, division) based on user input. Use loops to allow multiple calculations until the user decides to quit.

Related Tutorials

Learn about different data types and variables in C++.

Learn more

Learn how to create and use functions in C++.

Learn more

Learn how to work with arrays and collections in C++.

Learn more