DEV Community

Ishaan Sheikh
Ishaan Sheikh

Posted on • Updated on

C# loops

In this article, we'll learn about how to use loops in C#.

In C# there are 4 types of loops available -

  • for
  • foreach
  • while
  • do-while

The for loop

The for loop is a basic loop that is available in almost all programming languages. It executes a block of statements until a specified expression evaluates to false.

Syntax

for(initialValue; condition; iterator)
{
  statements...
}
Enter fullscreen mode Exit fullscreen mode

The above code executes the statements inside parentheses until the condition evaluates to false.

Example

for(int i = 0; i < 5; i++)
{
   Console.WriteLine(i);
}
Enter fullscreen mode Exit fullscreen mode

The foreach loop

The foreach loop in C# is used to iterate over the instance of the type that implements the IEnumerable or IEnumerable<T> interface. In other words, it is used to iterate over an array or collection.

Syntax

foreach(type variable in collection)
{
  statements...;
}
Enter fullscreen mode Exit fullscreen mode

Iterate on Array

In this example we'll use a simple array of integers.

int[] numbers = {1,2,3,4,5};
foreach(int number in numbers)
{
  Console.WriteLine(number);
}
Enter fullscreen mode Exit fullscreen mode

The above lines will print all the numbers in the list numbers.

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Iterate on Collection

In this example, we are going to use collections.

using System.Collections.Generic; 
...
...
List<string> people = new List<string> {"John","Smith","Josh","Walton"};
foreach(string name in people)
{
  Console.WriteLine(name);
}
Enter fullscreen mode Exit fullscreen mode

The above lines will print all the names from the collection people.

John
Smith
Josh
Walton
Enter fullscreen mode Exit fullscreen mode

The while loop

The while loop executes a block of statements while an expression evaluates to true.

Syntax

while(condition)
{
  statements...
}
Enter fullscreen mode Exit fullscreen mode

Example

int j = 0;
while (j<5)
{
    Console.Write(j);
    j++;
}
Enter fullscreen mode Exit fullscreen mode

The do-while loop

The do-while loop executes a block of statements while an expression evaluates to true. The only difference in this and while loop is that, it executes the block at least one time since the condition is checked after the execution of the loop.

Syntax

do
{
statements...
} while (condition)
Enter fullscreen mode Exit fullscreen mode

Example

int k = 1;
do
{
    Console.Write(k);
    k++;
} while(k<5)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)