For loop in Csharp
The for loop in CSharp is very similar to the while loop. It has the same functionality. At least regarding the counter type function. The for loop is preferred by most programmers though. Lets have a look at how a for loop is setup:
Syntax for a for loop in CSharp
for(int variable=startValue; variable<endValue; variable steps){ // executable code }
Now a concrete example for a for loop in csharp
for(int counter=1; counter<10; counter++){
Console.WriteLine(counter);
}
Console.Read();
Output:
1
2
3
4
5
6
7
8
9
For loops are very useful for counters or when you need to run through a list. As shown in the example our program now counts for us from 1 to 9. That’s because the start value was 1 and the code was repeated as long as counter was lower than 10. At 10 this is not the case anymore, so the code is not executed and we don’t get 10 as an output.
We can also count in bigger steps than just 1. E.g. if we want to get steps of 5 and the values from 0 to 45:
for(int counter=0; counter<=45; counter+=5){
Console.WriteLine(counter);
}
Console.Read();
Do you see how <=45 was used in order to also get the 45 as an output? That’s how easy it is. Then I use steps of 5 with +=5. That’s in general how you can add a certain amount to a variable with very little typing.