Loops and Iteration
8. Loops and Iteration
Loops allow a program to repeat actions without writing the same code again and again. This saves time, reduces mistakes, and makes programs shorter. Iteration is just a more formal word for repeating a process.
a. For Loop
A for loop is used when you know how many times you want something to repeat. It is common for counting, list processing, and going through a fixed range of values. Beginners usually learn this loop first because it is easy to control.
For example, if you want to print numbers from 1 to 5, a for loop can do that neatly. Instead of writing five separate lines, the loop handles the repetition automatically. For loops are very useful when the number of repetitions is already known.
b. While Loop
A while loop keeps running as long as a condition stays true. It is useful when you do not know exactly how many times the loop will repeat. The loop stops only when the condition becomes false.
For example, a program might keep asking for a password until the correct one is entered. In that case, the number of attempts is not fixed ahead of time. While loops are helpful for situations that depend on user input or changing conditions.
c. Break and Continue Statements
Break and continue are control statements used inside loops. The break statement stops the loop completely. The continue statement skips the current step and moves to the next repetition.
For example, if a loop is searching for a value and finds it, break can stop the loop early. If a loop should ignore one unwanted number, continue can skip that number and keep going. These statements help make loops more flexible and efficient.
d. Nested Loops
Nested loops mean putting one loop inside another. This is useful for working with rows and columns, patterns, tables, and multi-level data. Although they are very powerful, nested loops can become hard to read if overused.
For example, a program printing a table may use one loop for rows and another for columns. Another common use is generating pattern shapes with stars or numbers. Nested loops are often seen in beginner exercises because they teach how repetition can work in layers.










