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.
1#include <iostream>2using namespace std;34int main() {5 int number = 10;67 if (number > 0) {8 cout << "The number is positive." << endl;9 }1011 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.
1#include <iostream>2using namespace std;34int main() {5 int number = -5;67 if (number >= 0) {8 cout << "The number is positive or zero." << endl;9 } else {10 cout << "The number is negative." << endl;11 }1213 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.
1#include <iostream>2using namespace std;34int main() {5 int score = 85;67 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 }1819 return 0;20}
Nested if Statements
You can also nest if statements inside other if or else blocks to create more complex conditions.
1#include <iostream>2using namespace std;34int main() {5 int age = 25;6 bool hasLicense = true;78 if (age >= 18) {9 cout << "Person is an adult." << endl;1011 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 }1920 return 0;21}
Conditional (Ternary) Operator
The conditional operator ? :
provides a shorthand way to write simple if-else statements.
1#include <iostream>2using namespace std;34int main() {5 int number = 10;67 // Ternary operator syntax: condition ? expression_if_true : expression_if_false8 string result = (number % 2 == 0) ? "even" : "odd";910 cout << "The number is " << result << "." << endl;1112 // Equivalent if-else statement13 if (number % 2 == 0) {14 result = "even";15 } else {16 result = "odd";17 }1819 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.
1#include <iostream>2using namespace std;34int main() {5 char grade = 'B';67 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 }2627 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.
1#include <iostream>2using namespace std;34int main() {5 // Basic for loop6 for (int i = 1; i <= 5; i++) {7 cout << i << " ";8 }9 cout << endl;1011 // Output: 1 2 3 4 51213 // for loop with different increments14 for (int i = 0; i <= 10; i += 2) {15 cout << i << " ";16 }17 cout << endl;1819 // Output: 0 2 4 6 8 102021 // Countdown with for loop22 for (int i = 5; i > 0; i--) {23 cout << i << " ";24 }25 cout << endl;2627 // Output: 5 4 3 2 12829 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.
1#include <iostream>2#include <vector>3using namespace std;45int main() {6 vector<int> numbers = {1, 2, 3, 4, 5};78 // Range-based for loop9 for (int num : numbers) {10 cout << num << " ";11 }12 cout << endl;1314 // Output: 1 2 3 4 51516 // Range-based for loop with auto keyword17 for (auto num : numbers) {18 cout << num * 2 << " ";19 }20 cout << endl;2122 // Output: 2 4 6 8 102324 // Using references to modify elements25 for (auto& num : numbers) {26 num *= 3;27 }2829 // Print modified values30 for (auto num : numbers) {31 cout << num << " ";32 }33 cout << endl;3435 // Output: 3 6 9 12 153637 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.
1#include <iostream>2using namespace std;34int main() {5 int count = 1;67 while (count <= 5) {8 cout << count << " ";9 count++;10 }11 cout << endl;1213 // Output: 1 2 3 4 51415 // Example with user input16 int number;17 cout << "Enter a positive number: ";18 cin >> number;1920 while (number <= 0) {21 cout << "That's not a positive number. Try again: ";22 cin >> number;23 }2425 cout << "You entered: " << number << endl;2627 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.
1#include <iostream>2using namespace std;34int main() {5 int count = 1;67 do {8 cout << count << " ";9 count++;10 } while (count <= 5);11 cout << endl;1213 // Output: 1 2 3 4 51415 // Example where the condition is false initially16 int x = 10;1718 do {19 cout << "This will execute once even though the condition is false." << endl;20 } while (x < 5);2122 // Example with user input validation23 int number;2425 do {26 cout << "Enter a number between 1 and 10: ";27 cin >> number;28 } while (number < 1 || number > 10);2930 cout << "You entered a valid number: " << number << endl;3132 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.
1#include <iostream>2using namespace std;34int main() {5 // Using break in a for loop6 for (int i = 1; i <= 10; i++) {7 if (i == 6) {8 break; // Exit the loop when i equals 69 }10 cout << i << " ";11 }12 cout << endl;1314 // Output: 1 2 3 4 51516 // Using break in a while loop17 int count = 1;18 while (count <= 10) {19 if (count % 7 == 0) {20 break; // Exit when count is divisible by 721 }22 cout << count << " ";23 count++;24 }25 cout << endl;2627 // Output: 1 2 3 4 5 62829 return 0;30}
continue Statement
The continue
statement skips the rest of the current iteration and proceeds to the next iteration of the loop.
1#include <iostream>2using namespace std;34int main() {5 // Using continue in a for loop to skip even numbers6 for (int i = 1; i <= 10; i++) {7 if (i % 2 == 0) {8 continue; // Skip even numbers9 }10 cout << i << " ";11 }12 cout << endl;1314 // Output: 1 3 5 7 91516 // Using continue in a while loop17 int count = 0;18 while (count < 10) {19 count++;20 if (count % 3 == 0) {21 continue; // Skip numbers divisible by 322 }23 cout << count << " ";24 }25 cout << endl;2627 // Output: 1 2 4 5 7 8 102829 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.
1#include <iostream>2using namespace std;34int main() {5 // Using goto (generally not recommended)6 int i = 1;78start: // Label9 if (i <= 5) {10 cout << i << " ";11 i++;12 goto start; // Jump to the label13 }14 cout << endl;1516 // Output: 1 2 3 4 51718 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.
1#include <iostream>2using namespace std;34// Function that returns a value5int square(int num) {6 return num * num; // Exit the function and return the squared value7}89// Function with early return10bool isEven(int num) {11 if (num % 2 == 0) {12 return true; // Exit early if the number is even13 }1415 // This part only executes if the number is odd16 return false;17}1819int main() {20 cout << "Square of 5 is: " << square(5) << endl;2122 int number = 7;23 if (isEven(number)) {24 cout << number << " is even." << endl;25 } else {26 cout << number << " is odd." << endl;27 }2829 return 0; // Exit main function30}
Nested Loops
You can nest loops inside other loops to create more complex patterns and algorithms.
1#include <iostream>2using namespace std;34int main() {5 // Nested for loops to create a multiplication table6 for (int i = 1; i <= 5; i++) {7 for (int j = 1; j <= 5; j++) {8 cout << i * j << " ";9 }10 cout << endl;11 }1213 // Nested loops for pattern printing14 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 }2223 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.
1#include <iostream>2using namespace std;34int main() {5 // Infinite for loop6 // for (;;) {7 // cout << "This will run forever..." << endl;8 // }910 // Infinite while loop11 // while (true) {12 // cout << "This will also run forever..." << endl;13 // }1415 // Controlled infinite loop with a break condition16 int count = 0;17 while (true) {18 cout << "Iteration: " << count << endl;19 count++;2021 if (count >= 5) {22 cout << "Breaking out of the infinite loop." << endl;23 break;24 }25 }2627 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 moreLearn how to create and use functions in C++.
Learn moreLearn how to work with arrays and collections in C++.
Learn more