Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C#

Learn step by step



Loops

A loop is a way of repeating a statement a number of times until some way of ending the loop occurs. It might be run for a preset number of times, typically in a for loop, repeated as long as an expression is true (a while loop) or repeated until an expression becomes false in a do while loop.
Using a label, a Goto Statement can also create a loop by jumping backwards to a label though this is generally discouraged as a bad programming practice. For some complex code it allows a jump to a common exit point that simplifies the code.

  • while Loop
  • do loop
  • for loop
  • foreach loop

The While Loop

The while statement continually executes a block of statements until a specified expression evaluates to false . The expression is evaluated each time the loop is encountered and the evaluation result is true, the loop body statements are executed.


using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int number = 0;

while(number < 5)
{
Console.WriteLine(number);
number = number + 1;
}

Console.ReadLine();
}
}
}

output

01234
The do Loop

A do loop is similar to the while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time.


int number=0; do
{
Console.WriteLine(number);
number = number + 1;
} while(number < 5);

output

01234
The For Loop

The for loop in C# is useful for iterating over arrays and for sequential processing. This kind of for loop is useful for iterating over arrays and for other applications in which you know in advance how many times you want the loop to iterate. That is the statements within the code block of a for loop will execute a series of statements as long as a specific condition remains true. Every for loops defines initializer, condition, and iterator sections.


using System;

class ForLoop
{
public static void Main()
{
for (int i=0; i < 5; i++)
{

Console.Write("{0} ", i);
}
Console.WriteLine();
}
}

output

01234


Related Videos