Loop Controls In C# Complete Guide
Understanding the Core Concepts of Loop Controls in C#
Loop Controls in C#
1. For Loop
The for
loop is commonly used when the number of iterations is known beforehand. It consists of three main parts: initialization, condition, and increment/decrement.
Syntax:
for(initialization; condition; increment/decrement){
// Code to be executed
}
Example:
for(int i = 0; i < 5; i++){
Console.WriteLine("Iteration: " + i);
}
// Output: Iteration: 0, Iteration: 1, Iteration: 2, Iteration: 3, Iteration: 4
Explanation:
- Initialization:
int i = 0;
sets the starting point. - Condition:
i < 5;
defines whether the loop should continue or not. - Increment/Decrement:
i++
increments the loop variablei
after each iteration.
2. While Loop
The while
loop repeats a block of code as long as a specified condition is true.
Syntax:
while(condition){
// Code to be executed
}
Example:
int count = 0;
while(count < 5){
Console.WriteLine("Count: " + count);
count++;
}
// Output: Count: 0, Count: 1, Count: 2, Count: 3, Count: 4
Explanation:
- Condition: The loop continues until
count
is no longer less than 5. If the condition evaluates to false before entering the loop, the loop body will not execute at all.
3. Do While Loop
Unlike while
, the do while
loop ensures that the loop body executes at least once because the condition is evaluated after the first iteration.
Syntax:
do{
// Code to be executed
}while(condition);
Example:
int num = 0;
do{
Console.WriteLine("Num: " + num);
num++;
}while(num < 5);
// Output: Num: 0, Num: 1, Num: 2, Num: 3, Num: 4
Explanation:
- Execution: The loop runs at least once regardless of whether the condition
num < 5
is true. - Post Condition Check: After each iteration, the condition is checked to determine if the loop should continue.
4. Foreach Loop
The foreach
loop iterates over elements in an array or collection without needing an index variable.
Syntax:
foreach(var item in collection){
// Code to be executed
}
Example:
int[] numbers = {1, 2, 3, 4, 5};
foreach(int num in numbers){
Console.WriteLine(num);
}
// Output: 1, 2, 3, 4, 5
Explanation:
- Iterate Through Collection: Simplifies looping through arrays or collections by automatically handling the iteration index.
- No Index Modification: Elements in the collection cannot be modified directly using this loop; doing so will result in a compilation error.
5. Break Statement
The break
statement terminates the nearest enclosing for
, while
, do
, switch
, or foreach
loop immediately.
Syntax:
loop {
if(condition){
break;
}
// Code to be executed
}
Example:
for(int i = 0; i < 10; i++){
if(i == 5){
break;
}
Console.WriteLine("i = " + i);
}
// Output: i = 0, i = 1, i = 2, i = 3, i = 4
Explanation:
- Exit Loop: When
i
equals 5, thebreak
statement exits the loop.
6. Continue Statement
The continue
statement skips the current iteration and proceeds to the next iteration of the loop.
Syntax:
loop {
if(condition){
continue;
}
// Code to be executed
}
Example:
for(int i = 0; i < 5; i++){
if(i == 3){
continue;
}
Console.WriteLine("Number: " + i);
}
// Output: Number: 0, Number: 1, Number: 2, Number: 4
Explanation:
- Skip Iteration: When
i
equals 3, thecontinue
statement is executed, skipping the remaining part of the loop's body.
7. Goto Statement
Although not specifically a loop control, the goto
statement can be used to transfer control to any labeled statement, including exiting loops.
Syntax:
loop:
// Code to be executed
if(condition){
goto end;
}
end:
// Code to be executed after exit
Example:
int j = 0;
start:
if(j == 2){
goto end;
}
Console.WriteLine("Value of j : " + j);
j++;
goto start;
end:
Console.WriteLine("Exited loop");
// Output: Value of j : 0, Value of j : 1, Exited loop
Explanation:
- Unconditional Jump: The
goto
statement allows for jumping from one block of code to another. - Caution: Overuse can lead to spaghetti code, making it difficult to maintain.
8. Return Statement
The return
statement terminates the method and can be used inside loops to exit the method prematurely.
Syntax:
void MethodName(){
loop {
if(condition){
return;
}
// Code to be executed
}
}
Example:
void CheckNumber(int x){
while(x < 10){
if(x == 5){
return;
}
Console.WriteLine("x = " + x);
x++;
}
Console.WriteLine("Method finished");
}
CheckNumber(0);
// Output: x = 0, x = 1, x = 2, x = 3, x = 4
Explanation:
- Exit Method: When
x
equals 5, thereturn
statement exits theCheckNumber
method.
9. Try-Catch-Finally Block
These blocks handle exceptions within loops, ensuring code continues to run even if errors occur.
Syntax:
try {
// Code that may throw exceptions
} catch (ExceptionType ex) {
// Code that executes when an exception occurs
} finally {
// Code that always executes
}
Example:
int[] values = {1, 2, 0, 4, 5};
foreach(int v in values){
try {
Console.WriteLine(10 / v);
} catch (DivideByZeroException) {
Console.WriteLine("Cannot divide by zero!");
} finally {
Console.WriteLine("Processing complete for value: " + v);
}
}
// Output:
// 10
// 5
// Cannot divide by zero!
// Processing complete for value: 0
// 2.5
// 2
// Processing complete for value: 5
Explanation:
- Exception Handling: The
catch
block handles division by zero for the third element in the array, while thefinally
block executes regardless.
10. Nested Loops
Loops within loops allow for complex iterations, such as generating tables or iterating over multidimensional arrays.
Syntax:
outerloop:
// Code for outer loop
innerloop:
// Code for inner loop
Example:
for(int row = 1; row <= 3; row++){
for(int col = 1; col <= 3; col++){
Console.Write("* ");
}
Console.WriteLine();
}
// Output:
// * * *
// * * *
// * * *
Explanation:
- Outer Loop: Iterates rows.
- Inner Loop: Iterates columns, printing asterisks (
*
). - Row Break: After completing each column iteration, a newline character is added.
Conclusion
Online Code run
Step-by-Step Guide: How to Implement Loop Controls in C#
Loop Controls in C#
Overview
Loops in C# are used to execute a block of code repeatedly. Common loop constructs include for
, while
, and do-while
. Loop controls like break
, continue
, and goto
are used to alter the normal execution flow of these loops.
1. The for
Loop
The for
loop is used to execute a block of code a specific number of times.
Syntax:
for(initialization; condition; increment/decrement)
{
// code to execute
}
Example: Print numbers from 1 to 5
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
}
2. The while
Loop
The while
loop is used to execute a block of code as long as a specified condition is true.
Syntax:
while (condition)
{
// code to execute
}
Example: Print numbers from 1 to 5
using System;
class Program
{
static void Main()
{
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
}
}
3. The do-while
Loop
The do-while
loop is similar to the while
loop, but the block of code inside the loop is executed at least once before the condition is checked.
Syntax:
do
{
// code to execute
} while (condition);
Example: Print numbers from 1 to 5
using System;
class Program
{
static void Main()
{
int i = 1;
do
{
Console.WriteLine(i);
i++;
} while (i <= 5);
}
}
Loop Control Statements
1. break
The break
statement is used to exit a loop prematurely.
Example: Exit the loop when i == 3
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
break;
}
Console.WriteLine(i);
}
}
}
Output:
1
2
2. continue
The continue
statement causes the current iteration of the loop to end and jumps to the next iteration.
Example: Skip the number 3
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue;
}
Console.WriteLine(i);
}
}
}
Output:
1
2
4
5
3. goto
The goto
statement is used to jump to a different part of the code. It can be used to exit nested loops or to restart a loop.
Example: Use goto
to exit a nested loop
using System;
class Program
{
static void Main()
{
int i = 0;
start:
for (; i < 5; i++)
{
if (i == 3)
{
goto end;
}
Console.WriteLine(i);
}
end:
Console.WriteLine("Exited the loop");
}
}
Output:
0
1
2
Exited the loop
Conclusion
This guide covered the basic loops in C# (for
, while
, and do-while
) and how to control their execution using break
, continue
, and goto
. Understanding these concepts will help you write more efficient and effective C# code.
Login to post a comment.