C# for loop & Examples – C# Programming Example
For Loop

C# for loop & Examples

C# for loop

One usually uses a for loop when it is known how often certain instructions need to be executed. The general syntax of the for-loop construct looks like this:

The for loop consists of two components: the loop header, which describes the property of the loop, and the adjoining loop block, enclosed in curly brackets, containing the statements to be executed repeatedly. If this is only an instruction, the curly brackets can be omitted. To set the number of passes for a for loop, a loop counter is required whose
initial value is described by expression1.
The final value is defined in expression2,
and in expression3 it is finally determined to which amount the loop counter should be incremented on each loop pass.

For example:


c# for loop examples 1

c# for loop examples 1

The operation of the for loop

If the program flow encounters a for loop, expression 1 – also called an initialization expression – is evaluated first. This initializes the counter of the loop with a start value. The counter of the loop in our example is initialized with the start value 0.

Expression2, the conditional expression, evaluates the current state of the counter before each loop pass. In the example above, the condition is:

The conditional expression can be arbitrarily complex with the involvement of the various operators, but must always have a Boolean result. The statement block is executed only if expression2 is true, otherwise the program continues its execution with the statement following the loop block.

Expression3 (reinitialization expression) takes over the control of the loop counter. It is used to either increment or decrement the loop counter. In our case, the counter is incremented by +1. The increment occurs whenever the instruction block of the loop has passed. Afterwards, the conditional expression evaluates the new meter reading.

The counter variable

Basically, there are two ways to declare the counter variable that is used for the abort criterion:

inside the loop head
in front of the loop

Which notation you prefer depends on the visibility the meter should have. First, consider the following code snippet:

A counter variable declared in the loop header is considered to be a local variable of the loop and is therefore valid only within the for loop statement block. Therefore, accessing the counter from outside the loop also results in a compile error.

Therefore, if you implement multiple loops within a procedure such as Main, you must also re-declare the counter each time:

The better solution in this case would be the declaration of the counter variables before the first loop occurs:

Now that we have arrived at this point, the question arises as to whether, given a single for loop, concurrent declaration and initialization in the loop header is preferable to the early declaration of the counter variable before the loop header. There is no clear answer. For better clarity, however, it seems to be advantageous to make the declaration in the initialization expression.

for loops with any change of the counter

In most cases, an integer step size fully meets the requirements. But that is not always so. Sometimes smaller increments are needed, ie in the range of floating point numbers. Floating point numbers are always inherently inaccurate due to their nature. This can have particularly fatal consequences when grinding. Take a look at the following listing:

Normally we would not suspect at first glance – only when we run the program, we will find that the last counter value is missing:

The system-related inaccuracy of the floating point numbers causes the count in the last step is not exactly 2, but a little larger. This causes the second expression of the loop header to become false, causing it to prematurely exit the loop – the last loop pass required is not executed at all.

This thesis can be proved if the instruction to output to the console is replaced by the following:

We now force the output in exponential notation and specify an accuracy of 16 decimal places – then the type double at the 16th decimal place becomes inaccurate.

This error can be avoided if both the counter and the step size are made integer. In our example, the factor 10 sets the increment to +1. Similarly, the exit condition must be adjusted. To undo the effect on the output, we divide the date to be output by the same factor at the end.

Of course, the division also causes some inaccuracy, but that’s the nature of the floating-point numbers, which we have to accept. On the other hand, we have the certainty that at least the number of loop passes is correct.

The initialization of arrays in a  for  loop

As you can see, instruction sequences are executed repeatedly using for loops. This loop type is particularly useful for initializing array elements with specific values. Let’s make that clear with a simple example. The array list should be initialized with numbers that correspond to the square of the index of the element. The highest represented index should be entered by the user at the console. The code looks like this:

After the declaration of the array and the subsequent request to set the size of the array, the array is initialized according to the input of the user. The instruction for this seems to be relatively complex at first, but it is quite easy to interpret. It is – as well as the term makes – from the innermost parenthesis level, in the present case by the receipt of the user input:

The input of the user is a string, that is of the type string. Since the index of an array always has to be an int, we are forced to convert it:

Now, remember that by default, the input represents the highest index of the array, but we always specify the number of elements in an array initialization. To finally properly size our array, the converted user input must be increased by 1, so:

With the resulting number, the array can now be finally initialized in the capacity desired by the user.

Now follows the for loop. Since we want to assign the square of each index to each array element in the loop block, we let the loop counter run over all represented indexes – from 0 to the highest index. We determine the latter from the Length property of our array, which gives us the total number of elements. This is always 1 higher than the last index in the array. Therefore, the condition is the same

always the demands, because the loop is now run through until the number is reached, which is smaller than the number of elements. Equally, we could also formulate the following:

The loop header is now formulated according to the requirements, the instructions of the loop block are traversed as often as the array has elements. Since the loop counter has a counterpart in the form of an array index on every loop, we can use the counter to address each individual array element:

For the first run with i = 0, list [0] is assigned the number 0, the second run with i = 1 assigns the value 1 to the element liste [1], and so on.

The arguments of the “Main” method

So far, we’ve only started our programs with a simple call, either directly from the development environment or by specifying the filename at the input console. If we distribute an application, however, a user will never start the application from the development environment, but either by double-clicking on the EXE file in the Explorer, by entering the name of the executable file on the input console or via the Start • Execute option. ,

The latter two points open up even more possibilities: It is also possible to pass command line parameters as additional information to the main method, which are accepted in the array args in the parameter list of the Main method:

Let’s say we launch an application called MyApplication.exe on the console as follows:

The three transfer parameters “Peter”, “Willi” and “Udo” are received by Main in the string array args and can be used by the application for further operations. However, since the program does not know at runtime whether and how many parameters have been passed, the array args is first queried as to whether there is any valid element at all. If the number of elements is greater than 0, each array element can be accessed in a known manner using a for loop. Let’s take a look at a concrete example:

The if statement evaluates the Length property on args to see if the array is empty or not. If the user has passed at least one parameter, the for loop is executed, which outputs the contents of the parameter to the console.

Basically, all passed parameters are received as strings. But that should not stop us from handing over numbers if needed. However, we must not forget to use one of the methods of the Convert class to convert the string to the required data type.


C# for loop Examples

Example 1: Display Numbers Between 1 to 100 Using For Loop




Example 2: C# Program to Find the Factorial of a Number

Source Code:


Example 3: C# Program to Find GCD of Two Numbers Using For Loop

C# Code:

When you run the program, the output will be:

Example 4: Fibonacci Series in C# Using For Loop

Source Code:



Example 5: The Sum Of The First n Natural Numbers




Example 6: C# Console Application Program to Display Characters from A to Z Using Loop


When you run the program, the output will be:

Example 7: C# program to find min and max in an array



C# program using for loop to find maximum value from an array


Example 8: Click here for more for loop examples





Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: