Loops in C#
Loops, also called iteration statements, are essential programming constructs in C# that allow a block of statements to be continuously executed until a predetermined condition is satisfied. Because of this, repetitive operations can be completed quickly and effectively without requiring the draughting of the same code repeatedly.
There are four main kinds of iteration statements in C#:
- The
for
statement. - The
foreach
statement. - The
do
statement (ordo-while
loop). - The
while
statement.
You can use the continue statement to move on to the next iteration or the break statement to break out of the loop at any point in the body of an iteration statement. Because C# lacks a labelled break statement, analogous functionality like moving control to a specific switch-case label or exiting deeply nested loops is accomplished with the goto statement.
Here are examples of code to illustrate each type of loop:
for loop
The for loop is a type of repetition control structure that is intended to run a code block a certain number of times. It’s especially helpful when you know how many iterations there will be.
The three primary components of its syntax are the iterator, condition, and initialization:
- The initialization statement is only run once, at the start of the loop. A loop control variable that is scope-limited to the loop itself is usually declared and initialized here.
- A Boolean statement known as the condition is assessed before to every iteration. This condition must evaluate to true for the body of the loop to run. When false, the loop ends.
- After every iteration of the loop body, the iterator statement (also known as the increment) is run. The initialized variable’s value is usually altered. Commas can be used to separate a variety of expressions in this section, including assignment, method invocation, increment/decrement prefix/postfix, and object creation.
All three sections of a for
statement are optional, meaning for( ; ; ) { // Your code here }
creates an infinite loop.
Syntax
for (initialization; condition; iterator)
{
// Code block to be repeatedly executed
}
Example
using System;
public class ForLoopExample
{
public static void Main(string[] args)
{
// A simple for loop that counts from 0 to 4
Console.WriteLine("Counting from 0 to 4:");
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Current value of i: " + i);
}
}
}
Output
Counting from 0 to 4:
Current value of i: 0
Current value of i: 1
Current value of i: 2
Current value of i: 3
Current value of i: 4
foreach loop
A unique C# iteration statement made especially for iterating over array-type data and collections is the foreach loop. It does not have defined initialisation, termination conditions, or increment/decrement properties as for loops do. Navigating through every item in an array or collection is its main function.
A piece of code is run for every element in the collection by the foreach loop. The iterable-item is iterated over using the in keyword, which selects an item from it each time and stores it in a variable. The iteration variable functions as a read-only local variable; any effort to transmit it as ref or out, or edit it (using assignment or ++/– Operators), would result in a compile-time error. The foreach loop runs as many times as the number of elements in the collection.
Syntax
foreach (type variable in collection) { statements; }.
Example
using System;
using System.Collections.Generic; // Required for List<T>
public class ForEachLoopExample
{
public static void Main(string[] args)
{
// Using foreach with an array of strings
string[] colors = { "Red", "Green", "Blue", "Yellow", "Purple" };
Console.WriteLine("Iterating through an array of colors:");
foreach (string color in colors)
{
Console.WriteLine(color);
}
}
}
Output
Iterating through an array of colors:
Red
Green
Blue
Yellow
Purple
while loop
A statement or group of statements is repeatedly run by the while loop as long as a given Boolean condition is true. Since the condition is verified before the loop body is executed (making it an entry-controlled loop), if the condition is originally false, the loop body may not execute at all. The loop body should contain any increment or decrement steps, and the variables used in the condition should be initialised before the loop begins.
Syntax
while (condition)
{
// code block; or statement(s);
}
Example
using System;
public class WhileLoopExample
{
public static void Main(string[] args)
{
// Basic while loop: Counting up
Console.WriteLine("--- Counting Up with While Loop ---");
int count = 0; // Initialization
while (count < 5) // Condition
{
Console.WriteLine("Count is: " + count);
count++; // Iterator (update)
}
Console.WriteLine("While loop (counting up) finished. Final count: " + count);
}
}
Output
--- Counting Up with While Loop ---
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
While loop (counting up) finished. Final count: 5
do-while loop
With one significant exception the condition is evaluated after the loop body has been executed the do-while loop is comparable to the while loop in that it runs the code block at least once. As a result, the loop is exit-controlled. The Boolean condition must evaluate to true for the loop to continue running.
Syntax
do
{
// code block; or statement(s);
} while (condition); // Don't forget the trailing ;
Example
using System;
public class DoWhileLoopExample
{
public static void Main(string[] args)
{
// Do-while loop with user input (ensuring at least one prompt)
Console.WriteLine("--- Do-While Loop with User Input ---");
string password;
do
{
Console.Write("Enter your password (min 6 characters): ");
password = Console.ReadLine();
if (password.Length < 6)
{
Console.WriteLine("Password is too short. Please try again.");
}
} while (password.Length < 6); // Loop continues until password is at least 6 chars long
Console.WriteLine("Password accepted: " + password);
Console.WriteLine("Do-while loop (user input) finished.");
}
}
Output
--- Do-While Loop with User Input ---
Enter your password (min 6 characters): 181924
Password accepted: 181924
Do-while loop (user input) finished.
Nested Loops
One or more loops nested inside another loop are known as nested loops in programming. For every iteration of the outer loop, the inner loop runs through to the end. Out of all the loops, the innermost one runs the most, and the outermost one runs the fewest.
Nested loop types in C#
- Nested for loop.
- Nested while loop.
- Nested do-while loop.
Example
using System;
public class NestedLoopsExample
{
public static void Main(string[] args)
{
Console.WriteLine("Multiplication Table (up to 5x5):");
// Outer loop for rows (multiplicand)
for (int i = 1; i <= 5; i++) // The initialization statement is executed once at first
{
// Inner loop for columns (multiplier)
for (int j = 1; j <= 5; j++)
{
int product = i * j; // Perform arithmetic operation
// Display the product, formatted to align
Console.Write("{0,4}", product); // Uses composite formatting for spacing
}
Console.WriteLine(); // Move to the next line after each row is complete
}
}
}
Output
Multiplication Table (up to 5x5):
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Loop Control Statements
Break
Statement
By using this statement, the current loop iteration is automatically stopped. When a break occurs, program control returns to the statement that comes just after the loop. In addition to switch statements, it may be utilised in for, foreach, while, and do-while loops. Only the innermost loop in which break occurs is terminated in nested loops.
continue
Statement
The remainder of the current iteration’s code block is essentially skipped when this statement is used to exit the current loop condition and return to the beginning of the loop code. The loop then moves on to the following iteration, or for while and do-while loops, it reassesses its condition. It is applicable to switch statements and loops such as for, foreach, while, and do-while.
goto
statement
Program control is transferred straight to a labelled statement in C# using the goto statement. A legitimate identifier that comes right before the statement where control is to be transferred is called a label. Transferring control to a particular switch-case label or the default label inside a switch statement are examples of common usage. Additionally, it can be helpful for breaking out of highly nested loops.
In switch statements, this illustrates goto for fall-through behaviour, which C# doesn’t explicitly provide.
You can alos read What Are The Conditional Statements In C# With Code Examples