4. Repetition#

In the previous chapter, we discussed how to make decisions in C. In this chapter, we will discuss how to instruct the computer to repeat instructions. For example, we might want to print out the numbers 1 through 10. We could do this by printing out each number individually as in the following statement:

printf("1 2 3 4 5 6 7 8 9 10\n");

The issue with that is that it is prone to mistakes. For example, I can mistakenly write \(5\) twice. Also, it is also not very efficient. If I want to print out the numbers 1 through 100, I would have to write out 100 numbers. That is a lot of work!

Why do we need loops? We need loops to repeat a block of code multiple times. It is efficient and less prone to mistakes.

In this chapter, we will discuss the while, do while and for loops.