4 Let it flow – Conditions, iteration, and flow control
This chapter covers
- The benefits of a switch-case statement
- Introduction to loops and iteration
- Using while, do-while, and for loops
- The basics of using files in your code
C++ offers us various additional methods for controlling the flow of your code based on conditions and outcomes. In this chapter, we uncover more methods. In the previous chapter, you learned about the if-else statement, and how it can control the program’s flow while setting conditions. In this chapter, we explore another way to control the flow of our program using conditions, with the switch-case statements. The switch-case statement offers a more readable way to control the flow of your program through various conditions and potential outcomes, but it also has some pitfalls.
Next, we’ll delve into loops or iterations, which allow you to repeat sections of code multiple times. You’ll learn about different types of loops, including while loops that iterate while a certain condition is true, do-while loops that run once and then check the loop’s condition, and for loops that are great for controlling iterations by setting a sentinel or iterating a predefined number of times. We’ll also use for loops to introduce you to the concept of files and work with them in a coding exercise. Finally, you’ll learn about infinite loops, which is a loop state which iterates indefinitely or until someone stops them.