Repeated writing the same code is a poor process in C# and does not repeat yourself (dry) principle. But, there are many times in programming where you have to repeat commands, operations, or computations several times – perhaps changing every small thing.
From here the loops come. In this article, you will learn:
How to make your first loop
The benefits and warnings of the use of a loop
C# in different types of loops and how to use them
When it is better to use each one
The table of content
Let’s start. Open your preferred IDE or coding editor and create a new console application in .net 8+.
How to use for a loop in C
Repeats a block of code for a loop through which a fixed number:
Starting the loop variable.
Checking a condition before each repetition.
Update the loop variable after each repetition.
You can make a for Loop with the code given below:
var totalIterations = 5
for(int i = 0; i <= totalIterations; i++){
Console.Write($"{i},");
}
0,1,2,3,4,5,
Break it:
for– Declays the loopint i = 0;– Loop determines the starting point for variablesii <= totalIterations;– The condition of continuing looping. The code inside the loop operates only when it is true.i++– For short -handed “Increasei1 after each repetition 1 “
Repetition and zero
Why do you print six numbers for example? totalIterations Is 5? C# uses zero -based indexing. 0 → 5 counts include six numbers: 0,1,2,3,4,5.
Start if you want to print 1 → 5 instead i 1 on:
var totalIterations = 5;
for (int i = 1; i <= totalIterations; i++)
{
Console.Write($"{i},");
}
Indications:
Usually, for Collection uses loops for indicators/access of elements, so it is common practice to start and use your loop variables at 0 < (Minimum) a given number or length.
The direction of the direction
You can revers for Loop by starting at the end and decrease i:
for (int i = 5; i > 0; i--)
{
Console.Write($"{i},");
}
The loop checks if i > 0. After each repetition, i The number in the sequence is less than the printing number 1.
Other use for loops
We say you want to access every other item in a list. This is the place where the power is for Loops come in, and we can do more loop variableUsing it as index access.
public class Address
{
public string Name { get; set; } = string.Empty;
public string AddressLineOne { get; set; } = string.Empty;
public int HouseNumber { get; set; } = default;
public string PostCode { get; set; } = string.Empty;
public string Telephone { get; set; } = string.Empty;
}
internal class Program
{
public static void Main()
{
var addressBook = new List
{
new Address
{
Name = "Grant", AddressLineOne = "Developer Avenue", HouseNumber = 1, PostCode = "DV19 8EP",
Telephone = "0102919 93020-92019"
},
new Address
{
Name = "Bill", AddressLineOne = "Developer Avenue", HouseNumber = 19, PostCode = "DV19 8EP",
Telephone = "0102919 93020-92019"
},
new Address
{
Name = "Rebecca", AddressLineOne = "Developer Avenue", HouseNumber = 4, PostCode = "DV19 8EP",
Telephone = "0102919 93020-92019"
},
new Address
{
Name = "Amy", AddressLineOne = "Rower Avenue", HouseNumber = 1, PostCode = "DV19 8EP",
Telephone = "0102919 93020-92019"
},
new Address
{
Name = "Joe", AddressLineOne = "Olympic Drive", HouseNumber = 1, PostCode = "DV19 10E",
Telephone = "0102919 93020-92019"
}
};
for (var i = 0; i < addressBook.Count; i += 2)
{
Console.WriteLine($"Name: {addressBook(i).Name}, PostCode: {addressBook(i).PostCode}");
}
}
}
What is happening:
iStarts from 0 and increases from 2 (i += 2) Every repetitionaddressBook(i)Now accesses every other itemIt shows the power to use
iAs an index
So far we have seen how for Loops control the index and step size.
But sometimes you want to loop each item in a collection, without worrying about the index. The loop shines in this place.
How to use a loop of a priority in C
A foreach Loop repeats on anything that is inherited IEnumerable (Lists, rows, collections). It automatically accesses each item in order, so you don’t need the index.
How to write a prediction loop
var characters = new List<string>{"Batman", "CatWoman", "The Joker","Harley Quinn"};
foreach(var character in characters){
Console.WriteLine(character);
}
Key points:
The indicators are not required
Works with any competent collection
Clean, more expressive code
Predicted loop warnings
No indicator making
You cannot access items directly addressBook(i) The reason for this within a prediction is that foreach Works IEnumerableWhich does not expose the index.
Efficiency
A foreach There is a small overhead than the loop for Loop does not matter in most cases, but in the main code of performance, A for The loop can be faster.
To modify items
foreach Provides you a copy of the existing item, not direct reference. This means that you cannot re -assign values ​​to the list of lists within the loop.
foreach It is ideal when you want to go on each item, but not control over the number of repetitions.
How to use DO
do..while Loops run at least once the code, then repeat while no condition is correct:
int num;
do {
Console.Write("Enter a positive number: ");
num = int.Parse(Console.ReadLine());
} while (num <= 0);
Console.WriteLine(num);
The above code requests to enter a number within the console application if the condition is fulfilled. That is, if a positive number is provided, the code will not ask for another, exiting the loop.
If the user enters the negative number, it will continue to loop, and request to enter a positive number.
If you didn’t want the code to run at least once, and only if a condition was fulfilled? This is where you can use A while Loop
How to use a little while in C
while Loops repeats the code code unless a condition is correct, but if the condition is initially incorrect then the body can never run:
We can use the Darts Scoreboard example:
var sum = 0;
var dartsThrown = 0;
var random = new Random();
while (sum < 180 && dartsThrown < 3)
{
var dartScore = random.Next(61);
sum += dartScore;
dartsThrown++;
}
Console.WriteLine("Your score is " + sum);
Although the player has darts to throw, the code will randomly select a number and increase their score.
Indications: Always add the code that changes the condition, or you are at risk of making an unlimited loop. An unlimited loop, a loop that never stops, and causes your request to break.
You have seen four different ways of repeating the code in C#: forFor, for, for,. foreachFor, for, for,. do..whileAnd while. Let’s summarize when to use everyone.
Final views: Choosing the right loop
C# gives us many types of loops. The correct choice makes your code worth reading, efficient and deliberately.
For a loop: When you know how often to drive something, or use when you need an index, such as using ends, leoping items. Use A
forLoop when you need more control over the upheaval nature of the loop.Forte Loop: Use when you want to repeat through each item in a collection without worrying about the index.
While loop: When you do not know how often to run the code, but a condition runs the loop.
Do .. that loop: When the loop body should run at least once, such as the user’s input or for a re -attempting logic.
With the loop type with your intention, your code will be right, able to read and maintain.
I hope this lesson was useful, and as always I would love to listen to your thoughts and talk more on social media. You can find me Twitter/x.