Code Repetition
Programs often need to do the same thing many times. Say you want to print a countdown from 5 to 1:
Console.WriteLine("Launching in 5...");
Console.WriteLine("Launching in 4...");
Console.WriteLine("Launching in 3...");
Console.WriteLine("Lauching in 2...");
Console.WriteLine("Launching in 1...");
Console.WriteLine("Liftoff! 🚀");
Did you spot the typo? It's easy to miss when the same line is copied over and over. Now imagine:
- Changing "Launching" to "Starting" means editing 5 lines.
- Counting down from 100 means writing 100 lines.
- Letting the user choose the starting number is impossible, since you can't know in advance how many lines to write.
The Solution: Loops
A loop lets you write code once and have the program repeat it for you. C# gives you three main loop structures:
- While loops
- Do-While Loops
- For loops