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.

4.1 Switch craft – using switch-case statements

4.1.1 The brotherhood of if-else, the ternary operator, and the switch case

4.2 Looping–- the art of repetition

4.2.1 The basic principles for loops

4.2.2 While loop – looping while a condition is true

4.2.3 Do while: the post-step loop

4.2.4 For the love of loop – the for loop

4.2.5 The infinite loop

4.3 Final exercise: solve the jug puzzle

4.4 Summary