loops c# code example
Example 1: how to make a for loop in c#
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Value of i: {0}", i);
}
Example 2: for loop c#
/* for( declartion ; question ; operation )
the semi-colon(;) is a must but the declation, question and opertion is not
the declation question and operation can be swaped to your liking
and even removed completly */
// examples:
for(int i = 0; i < 3; i++) // output:
{ // Hi
Console.WriteLine("Hi"); // Hi
} // Hi
for(int i = 0; i < 3; i++) // output:
{ // 0
Console.WriteLine(i); // 1
} // 2
// pay attention to this question it's <= instead of <
for(int i = 5; i <= 8; i++) // output:
{ // 5
Console.WriteLine(i); // 6
} // 7
// 8
for(int i = 3; i > 0; i--) // output:
{ // 3
Console.WriteLine(i); // 2
} // 1
for(;;) // this will result in an infinite loop
{
// code here
}
Example 3: c# for loop example
for (int i = 0; i < 2; i++)
{
for(int j =i; j < 4; j++)
Console.WriteLine("Value of i: {0}, J: {1} ", i,j);
}
Example 4: c# loops
// ------------------- Syntax of Loops ---------------------- //
// ----- FOR LOOP ----- //
// for (start value; condition; increment)
for (int i = 0; i < 10; i++) {
Console.WriteLine(i);
}
// ----- WHILE LOOP ----- //
// start_value = 0; while (condition) { increment++ }
int counter = 0;
while (counter < 5) {
Console.WriteLine(counter);
counter++;
}
// ----- DO WHILE LOOP ----- //
// start_value = 0; do { increment++ } while (condition);
int counter = 0;
do
{
Console.WriteLine(counter);
counter++;
} while (counter < 5);
// ----- FOREACH LOOP ----- //
// for (item in list/array)
string[] myArray = { "grape", "orange", "pink", "blue" };
foreach (string item in myArray) {
Console.WriteLine(item);
}
Example 5: c# for loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
______________OUTPUT____________
0
1
2
3
4
Example 6: loop in c#
public class MyClass
{
void Start()
{
//Called when script inithilizes
}
void Update()
{
//called each fram
}
}
//note this is in C