GST Billing Software

1. While Loop 2. The do loop 3. The for loop For loop preferred when you know how many iterations you want, either because you know the exact amount of iterations, or because you have a variable containing the amount. for (initialization; condition; increment or decrement) { } 4. The foreach loop The foreach loop in C# executes a block of code on each element in an array or a collection of items. When executing foreach loop it traversing items in a collection or an array. The foreach loop is useful for traversing each item in an array or a collection of items and displayed one by one. Foreach (variable type in collection) { // code block }

header image

Loops

Erachana Line

Looping - The ability to repeat a block of code X times. In C#, they come in 4 different variants.

The while loop simply executes a block of code until condition is true.

Syntax:

While(condition)

{

}

Example:

using System;

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

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

Console.ReadLine();
}
}
}

Output: You will get list of numbers, from 0 to 4.

The number is first defined as 0, and each time the code in the loop is executed, it's incremented by one.

The do loop works like the while loop. The do loop evaluates the condition after the loop has executed, which makes sure that the code block is always executed at least once.

Syntax:

do

{

} While(condition);

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

The output is the same though - once the number is more than 5, the loop is exited.

Syntax:

example.

using System;

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

for(int i = 0; i < number; i++)
Console.WriteLine(i);

Console.ReadLine();
}
}
}

This produces the exact same output as previous.

For loop consists of 3 parts - we initialize a variable for counting, set up a conditional statement to test it and increment or decrement the counter (++ means the same as "variable = variable + 1").

The first part, where we define the i variable and set it to 0, is only executed once, before the loop starts. The last 2 parts are executed for each iteration of the loop. Each time, i is compared to our number variable - if i is smaller than number, the loop runs one more time. After that, i is increased by one.

Syntax:

Example:

using System;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add("John Doe");
list.Add("Jane Doe");
list.Add("Someone Else");

foreach(string name in list)
Console.WriteLine(name);

Console.ReadLine();
}
}
}