Looping

[print-me]

Looping allows you to repeat a set of code or statements while a given condition is true. Without it, you have to write multiple similar codes just to make your program repeat and that is tedious. Suppose you want to print “Hello World.” 10 times. It will look like this without using a loop.

Console.WriteLine("Hello World.");
Console.WriteLine("Hello World.");
Console.WriteLine("Hello World.");
Console.WriteLine("Hello World.");
Console.WriteLine("Hello World.");
Console.WriteLine("Hello World.");
Console.WriteLine("Hello World.");
Console.WriteLine("Hello World.");
Console.WriteLine("Hello World.");
Console.WriteLine("Hello World.");

Of course, you can copy the first line and just hit Ctrl + V to paste the other nine, but what I’m trying to show you here is inefficiency. There is a way to better write all of these lines of code and that’s by using a loop. There are different kinds of looping structure in C#.

  • while Loop
  • do while Loop
  • for Loop