epicours/Prog/Loops.md

887 B

In C#, loops are called iteration statements. We need to master both, recursion and loops. There are 3 kinds of loops in C# :

  • while and do (...) while
  • for
  • foreach

While loop

while (<condition>)
{
	// repeat stuff
}

The condition is a boolean Example

unit SumWhile(unit n)
{
	uint loop = 0;
	while (n > 1)
	{
		loop += 1;
		n = n - 1;
	}
	return loop;
}

Iteration statements - do (..) while

do 
{
	// Repeat stuff
} while (condition)

Same thing that the other one but return in a different way Example

uint SumDoWhile(uint n)
{
	uint loop = 0;
	do
	{
		loop += 1;
		n = n - 1;
	} while (n > 1):
	return loop;
}

For loop

for ([initialize]; [condition]; [iterator])
{
	// Repeat stuff
}

Example:

uint SumFor(uint n)
{
	uint res = 0;
	for (uint i = 1; i < n; ++i)
	{
		res += 1;
	}
	return res;
}