For loop in C # - how it works
You need a for loop regularly in C # programs. We explain how it works.
Create for loop in C #
A for loop in C # is always built on the same principle: it begins with the term "for" and the conditions in parentheses: "for ()"
- In the parentheses you first enter the data type of the run variable (such as "int", "short" or "float") with the start value (underlined in red in the figure). A semicolon closes the start value definition. You can find an overview of data types in C # in this practical tip.
- Now define the termination condition (underlined in orange in the picture). It is often the case that the run variable reaches a certain value. The termination condition can also refer to other variables. You also separate this part from the rest with a semicolon.
- Finally you define what should happen after each loop pass (underlined in green in the picture). This is often an increase or decrease in the run variable. "++" is synonymous with "+ = 1". You can also change other local variables after each run.
- If the code of the for loop extends over several lines, you have to put curly braces around the outside.
- A danger point with for loops is the endless loop: Always make sure that the abort condition will occur at some point.
- It is particularly easy to create for loops in editors such as "Visual Studio Express" or "Notepadd ++", because these editors highlight commands in color and display a message if undefined variables are accidentally used.
- For a better understanding of for loops, explanations of the for loop in other programming languages will help you, such as the practical tip on the for loop in Java or our video on the loop in Objective C:
You can get help with programming and for your first C # program as well as links for online programming in other CHIP practical tips.