Looping – For loop

October20, 2017
by admin

For loop is used when you want to repeat the set of statements or commands at a fixed number of times. That means you have already know how many times the loop should repeat.

Syntax:

for(<data type> <variable>=<initial value>; <conditional expression>; 
    <variable increment or decrement>)
{
  // statement or statements
  // to be executed
}

Look at the syntax of the for loop. It starts with ‘for’ keyword. Then you have to open and close the parenthesis. Within the parenthesis there are three arguments.

The first argument is the initialization. Here we do the initialization of the variable along with its declaration.

Ex:

int x = 0;

The second argument is the conditional expression that informs the compiler how many times should repeat this loop.

Ex:

x <= 10;

Here this loop should execute for statements or repeat the for loop for a fixed number of times that is 10. As soon as the value of x is 10 or more than 10, condition will return false and the loop will terminate. You can have a variable to compare instead of a literal value.

Ex:

x <= y;

The third argument is about increment or decrement of for loop variable.

Ex:

x++;
or 
x--;

Here x++ will increment the value of x by 1 every time the statement executes. While x-- will decrement the value of x by 1 every time the statement executes or in simple word after each repetition of for loop.

Please note that incrementing or decrementing the value of for a counter variable by 1 is the most used behavioral and required, but you can have increment or decrement value by more that 1.

Ex:

x = x + 2;
or 
x = x - 2;

Lets understand the for loop by simple code examples.

Ex 1:

Problem:

Write a program to display numbers from 1 to 10 in sequential order to console output each on separate lines.

Solution:


  using System;

  namespace LoopingDemo
  {
    public class Fordemo
    {
      public static void main()
      {
        for(int x =1; x <=10; x++)
        {
          Console.WriteLine(x);        
        }

        Console.WriteLine("Enter any key to exit");
        Console.ReadKey();
      }
    }
  }

Output:

1

2

3

4

5

6

7

8

9

10

In above code example, we have to print numbers from 1 to 10 in sequence to the console output. So we choose the for loop since we know that loop should repeat the statements for 10 times only. We have done declaration and initialization as follows.

int x =1;

Here we have declared variable 'x' of 'int' data type with initial value of 1.

We could also use the value of x to 0 but since the first value that we need to print is 1, we preferred 1 over 0.

Then we have a conditional expression in for loop as follows.

x <= 10;

That tells the compiler that this loop should execute or repeat till the value of variable 'x' is less that or equal to 10. As soon as the value of x changes to 10 or more than 10 this for loop should terminate.

Then in the last argument of for loop, we have incremented the value of 'x' by 1, using increment operator.

x++;

Note that we can also write it as x = x + 1.

Now we have our arguments written. Next within the body of for loop, we have printed the current value of variable 'x' to the console output using System.Console.WriteLine() method. This will display each value of x in the separate line. This is the only statement we required in this example.

After executing for loop and displaying output to the user, we simply asked the user to press any key to exit the application.

When you compile and run the application you will see the output as shown in the output section.

Lets now understand the flow of for loop within the above code example so that you can have a strong knowledge how the for loop works in C#.

When control flow goes first time to the for statement, it first executes the declaration and initialization statement (1st argument of for statement).

int x = 1; 

It declares variable 'x' as an integer data type and initialize it with value 1.

Then it moves to conditional expression and executes it (2nd argument of for statement).

x <= 10;

Since current value of 'x' is 1 which is less than 10, expression returns true. So control flow enters the body of for loop and executes the following statement.

Console.WriteLine(x); 

It prints the value '1' to console output.

After executing the statements from for loop, control again goes to the for statement.

Now it first executes increment or decrement statement as follows (3rd argument of for statement).

x++;

It increases the value of variable 'x' by 1. Now the current value of x is 2.

After executing increment/decrement expression control flow again executes the conditional expression to check whether it returns true or false for the new value of counter variable 'x'.

x <= 10;

Since 2 is less than 10, expression returns true and enters into the body of for loop and execute the statements to print the current value of 'x' to the console output.

It prints the value '2' on the new line to console output.

After executing the statements from for loop, control again goes to the for statement.

Again, it executes the increment/decrement statement and then executes the conditional expression to check whether it returns true for the current value of counter variable.

This cycle repeats until conditional expression returns true.

When the value of variable 'x' becomes 10, for loop statement prints the value 10 to the console output. After printing value 10 control flow goes to the for statement.

First, it executes increment/decrement statement as follows.

x++;

This increases the value of counter variable 'x' by 1.

Now the current value of 'x' is 11. Then control flow executes the conditional expression as follows.

x <= 10;

Since the current value of x (11) is not less than or equal to 10, the expression returns false and control flow jumped out of for statement and executes the immediate next statement after closing curly braces of for loop.

Till now there are 1 to 10 values printed to the output. So we asked the user to press any key to exit the application with the following code.

Console.WriteLine("Enter any key to exit");
Console.ReadKey();

This completes our code flow for 'for' loop.

Lets see another similar example of for loop, but with decrementing the value of counter variable.

Ex 2:

Problem:

Write a program to display numbers from 1 to 10 in reverse order to console output each on separate lines.

Solution:


  using System;

  namespace LoopingDemo
  {
    public class Fordemo
    {
      public static void main()
      {
        for(int x =10; x >=1; x--)
        {
          Console.WriteLine(x);        
        }

        Console.WriteLine("Enter any key to exit");
        Console.ReadKey();
      }
    }
  }

Output:

10

9

8

7

6

5

4

3

2

1

In the ex. 2, we need to print the numbers 1 to 10 as in the ex 1, but this time in reverse order i. e. first, we need to print 10 and then 9 and then 8 till 1. To achieve this we have modified the for statement as follows.

for(int x =10; x >=1; x--)

Then first change we made is in the declaration and initialization of the counter variable as follows.

int x = 10;

Since we need to print values from 10, we have initialized value of 'x' to 10.

The second change we made is at the increment/decrement statement. Instead of increment operator, we have used decrement operator since we need to decrement the value of x by 1 with every iteration of for loop.

x--;

The third change we made is in the conditional expression since we need to execute for statements till the value of x is greater than or equal to 1. As soon as the value of 'x' becomes less than 1, for loop should terminate.

x >= 1;

With these changes when we compile and run the application, it shows the output as expected and prints values 1 to 10 in reverse order.

In this and every for loop, the control flow is same as discussed in ex: 1.

First iteration of for loop:

At the beginning of for loop, i. e. when for loop executes for the first time, the counter variable is declared and initialized. This executes only once.

for(int x =10; ; ) 

Then it executes the conditional expression and if it returns true, control flow executes statements within the body of for loop. If it returns false, control flow terminates the for loop and jump out of for loop to execute the very next statement after closing curly braces of for loop.

for( ; x >= 1; ;)

Second and every successive iteration of for loop:

Executes Increment/decrement statement.

for( ; ; x--)

Executes conditional expression:

for( ; x >= 1; ;)

Hope that you understand the flow of for loop and will be able to understand how it works for any for loop coding whether it is for simple or complex problem.

C# Fundamentals