Loading ...

C# for loop

 /5
0 (0votes)

The "for" loop enables the user to iterate through a series of values to perform a task a specified number of times.

In order to implement "for" loop, one should know in advance about how many times the loop is to be executed.

It is also called count controlled loop.

 Syntax of for loop is:

 for(initialization,conditional expression,increment)
 {
   statement
 }

 
  where
  for : is a reserved word in c#
  initialization: is usually an assignment expression wherein a loop contol variable is initialized.
  conditional expression:  required to check whether the loop should be continue or be terminated
  increment: it modifies the value of loop control by a certain value

  statement: can be simple or compound statement

example of for loop


for ( int i = 1;i < 10; i++)
{
  Console.WriteLine(i);
}

Output will be:

1
2
3
4
5
6
7
8
9


Infinite for loop:

 All the expressions of for loop are optional.
 for example we can write like this the loop will be executed infinite times

  for(;;)
  {
  Console.WriteLine("Hi");
  }

In the above example Hi will be executed infinite times.

Nested for loops:

We can also do the nesting of for loops.There can be a for loop inside a for loop.

  for(int i=i ;  i<25; i++)
 {
   System.Console.WriteLine (i);
   for(int j=1 ; j<10; j++)
   {
   System.Console.WriteLine (j);
   }
  }


In the above example the value of i is from 1 to 24 and the value of j is from 1 to 9.


Using Continue statment in for loop:

If "continue" statement is used in "for" loop, it skips all the remaining code after the "continue" statement in the "for" loop and starts execution from the beginning of the loop.


   for (int i = 1; i < 20; i++)
  {
          if ((i % 2) != 0)
               continue;

           System.Console.WriteLine ( "value of i is = " + i);
   }


The output is

2
4
6
8
10
12
14
16
18
20

If the remainder is not zero, the "continue" statement will be exceuted.The control will start from the begining.

 

 

Comments (no comments yet)

  • :*
  • :*
  • :
 *

Top Posts