shopify traffic stats

How to create C# Loops

The For Loop.

For loops are good when I need to loop through some code for a set number of times.  

Structure:

for (variable name = a number; a condition to meet; how many times)

{
the code that I want to repeat
}

Example:

for (int tictacs = 1; tictacs <= 10; tictacs++)

{
Console.Writeline(“I just ate {0} Tictacs”,tictacs)
}

Here is the result.

C# for loop result

The While Loop

 The while loop loops through code based on a condition.

Structure:

while (variable <= a number)
{
process some code
}

Example:

//create an integer variable called MattsNumber and set it’s value to 1
int MattsNumber = 1;

//start the while loop.  While MattsNumber is less than or equal to 10 execute the code in the braces below.
while (MattsNumber <= 10)

{
//Increment MattsNumber by 1 every time we go through the loop.
MattsNumber++;
//Write some text and include what number we’re on
Console.Writeline(“The number is: {0}”,MattsNumber);

}

Console.Readline();

Here is the result:

c# while loop

The last loop for this post is the “Do While” Loop.  The do while loop is almost exactly the same as the while loop EXCEPT the code in the {} WILL RUN at least 1 time (even if the condition for the while loop is false).

Structure:

do
{
process some code
} while (variable <= a number);

Example

int MattsNumber = 1;

            do {

                MattsNumber++;

                Console.WriteLine(“The number is now {0}”, MattsNumber);

            } while (MattsNumber <= 10);

            Console.ReadLine();

Here is the result:

c# do while loop

Share This
%d bloggers like this: