What is a Loop?
In programming, a loop is one basic control structure used by programmers to repeat a block of code depending on a stated condition. Some of the most common tasks require repetitive actions, that is, when we’re processing things in a collection, calculating something several times, or waiting to do something until a given condition is met.
The use of loops reduces code repetition, and they save us from writing the same thing several times. Instead of repeating the same code several times, we run the same piece of code once and reuse next time. It makes our code clean and easy to read and also increases the efficiency of the code. C# offers a number of various types of loops for various situations.
The while Loop
One of the simple forms of loops in C# is while loop. That repeatedly repeats a block of code until a condition is true. In the loop, the condition evaluated before each iteration, if it’s true the loop body is executed. The loop terminates and the control pass only to the following statement after loop if the condition is false.
The while loop has especially great use when we are not sure of the number of iterations beforehand, and its value depends on dynamic conditions at runtime. It is a simple way of executing a task until a condition is no longer true.
int counter = 1;
while (counter <= 5)
{
Console.WriteLine("Counter: " + counter);
counter++;
}
Here the loop would print the value of counter from 1 to 5. counter is less than or equal to 5; the loop is running until it gets broken from there. In each iteration counter is incremented with 1. When counter gets to 6, if we compare counter <= 5, we will throw counter as it is false (less than) and ending the loop.
The do-while Loop
The do-while loop is similar to the while loop but with one key difference: With it, we can guarantee that the loop body at least runs once. In do while loop condition will be checked after running the loop body. What that implies is even if the condition is false on the first check the loop body will run once anyway.
If used when you need the code block to be executed at least once (e.g. when you need to prompt a user for input, validate the input in the loop).
int number;
do
{
Console.WriteLine("Enter a number greater than 10:");
number = Convert.ToInt32(Console.ReadLine());
}
while (number <= 10);
Console.WriteLine("You entered: " + number);
And in this case, the program asks the user to enter a number greater than 10. The do while loop makes sure it will show at least once. The loop prompts the user to enter a number if the entered number is less then or equal to 10, otherwise the loop stops.
The for Loop
A for loop in python is a control structure which implements a block of code on repeated basis i.e with a counter. If you know how many iterations to perform beforehand, very often people use it. The for loop has got everything that you need for just a one liner — initialization, condition check, and iteration expression is all in one line, and hence is compact and easily manageable.
The structure of a for loop includes three parts:
- Initialization: Starts the value of loop control variable.
- Condition: It decides whether to continue the loop running.
- Iteration: Up dates the loop control before each iteration.
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Iteration: " + i);
}
In that case, the loop will repeat five times and will print the iteration number from 0 to 4. i starts from 0 in the loop, if i is less than 5 it will increment i by 1 at the end of each iteration. Then, after i reaches 5 the condition becomes i < 5 and therefore made false, stopping the loop being executed.
The foreach Loop
It is used to iterate over elements in collection or array. It simply makes the process of walking through top items really easy, removing the need for a counter or index variable. Each element in the collection is automatically looped through — the loop body is executed on each item.
The beauty of this loop is that it allows you to step in and out of this loop without changing the collection itself. The existence of this library makes code more readable and lessens the problems of errors with managing index.
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine("Fruit: " + fruit);
}
The fruits Array is passed to the foreach, and prints each fruits name inside of it. By assigning each element in the array to fruit when the loop iterates, it becomes much easier to read and less code itself.
What is a Nested Loop?
A loop nested in another loop is called when a loop is run inside the body of another. The outer loop executes only once, and the inner loop is executed completely every time. They’re good for working with multi dimensional data structures such as two dimensional arrays and for performing complex iterations that involves multiple levels of looping.
Nevertheless, the increased computational complexity caused by nested loops can be prohibitive, provided they are not doing it properly. When it comes to performance, one should always find the reason why nested loops are required and if they are optimized enough is.
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("Outer loop iteration: " + i);
for (int j = 1; j <= 2; j++)
{
Console.WriteLine(" Inner loop iteration: " + j);
}
}
In the example above, for each iteration of the outer loop, it runs three times and for each outer iteration of the inner loop it runs twice. Overall this allows for six iterations of the inner loop. Once you have created the nested loops, which interact, the output will be how nested loops work.
The break Statement
Becomes a break statement which terminates the flow of a loop. The break statement causes control immediately exit the loop and immediately resume execution just after the loop. When loop has to stop processing further iterations under a certain condition it is useful.
break can be useful, checking to see if we need to perform unnecessary iterations if we already achieved the desired condition. Though this should be used sparingly to keep the logic flow graceful and the readability, but it should be used judiciously.
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine("Number: " + i);
}
This example has the loop from 1 to 10. But, if the loop starts, the break statement will be run when i = 5, and the loop will get done. The behavior is such that we print numbers 1 through 4, and then exit the loop before we print 5 through 10.
The continue Statement
The continue statement causes that process iterated in a loop to skip to a next iteration. The loop executes normally when continue is seen, it skips the body of the loop within that iteration and the loop continues to exist. Here, looping is useful when some conditions need the loop to skip over some iterations without stopping completely.
In the situations when you want to just ignore some values or conditions during the loop and continue handling with the rest of the items, this statement is helpful.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue;
}
Console.WriteLine("Number: " + i);
}
In this example, the continue statement to the loop will make the loop to skip out using the Console.WriteLine call for each iteration as an example i equals 3 would cause the loop to skip the Console.WriteLine call for that given iteration. Therefore, 1, 2, 4 and 5 are printed and 3 is omitted.
The return Statement
return statement exits a method and implicitly returns the value back to the caller. Using return however, will cut off execution of the entire method if it detects a specific condition within a loop’s context. Sometimes, it’s a quicker way to get out of a method as soon as a certain kind of result is accomplished.
Although return within loops is supported, including this directive inside loops helps make the method flow less readable when abused or inconsistently used.
static int FindFirstEven(int[] numbers)
{
foreach (int number in numbers)
{
if (number % 2 == 0)
{
return number;
}
}
return -1; // Indicates no even number was found
}
FindFirstEven is a method in this example, for finding the first even number in an array. If we find an even number, the return statement leaves the method right away and it’ll return that number. If after executing the loop there is no odd number, the method returns -1.
The throw Statement
The throw statement is used for throwing exception during the running of a program. When a throw statement is executed it causes control to transfer to the nearest suitable exception handler. throw can stop execution inside a loop when an unsolvable problem comes up that cannot be dealt with inside the loop.
With throw, we are able to have robust error handling since we have a way of catching and handling exceptions nicely.
static void ValidateNumbers(int[] numbers)
{
foreach (int number in numbers)
{
if (number < 0)
{
throw new ArgumentException("Negative numbers are not allowed.");
}
Console.WriteLine("Number: " + number);
}
}
With this example, method ValidateNumbers takes an array of integers as input. The throw statement, thrown if a negative number is encountered, raises an ArgumentException, to indicate that negative numbers are not allowed. Then this exception will be caught by the calling code and handled to raise the hope that the program won’t crash unexpectedly.
Learning and using these various loops and control statements in C# gives programmers a strong start in writing good and efficient readable, and robust code. They are powerful tools that make loops very powerful tools if used effectively to give applications a whole lot more functionality.