The for loop can consist of up to three parts:
It looks like:
for(int i=0;i<10;i++)
{
Console.WriteLine("variable i has value " +i);
}
At the beginning of the loop we create a variable i with a value of 0 in the second part we set the looping condition which says that until variable i is less than 10, the code should be executed in
the curly brackets of this loop, the third condition, the operation on the initial condition says that if variable i
still is smaller than 10, after each loop execution, the variable is to be incremented by 1, so this condition will be executed 10 times and will end with 9 because condition until and less than 10 to 10 would be if the condition was less than or equal to.
if we would like an infinite for it is enough to give such a condition that will never be fulfilled e.g.
for(int i=0;i<10;i--)
{
Console.WriteLine("variable i has value " +i);
}
However, you can do it in a simpler and clearer way, simply do not insert any conditions.
for(; ;)
{
Console.WriteLine("Executing a loop in progress");
}
The while() loop is based on the fact that the while loop is executed until the looping condition given in parentheses is true. Example:
int a = 0;
while(a<=20)
{
Console.WriteLine(a);
a++;
}
Console.WriteLine("The end loop");
In this loop until variable a is equal to 20 the variable a will be incremented by 1 every time the loop will passes
Now let’s look at this example:
string reply = "";
while(true)
{
Console.WriteLine("Exit the loop? [Y/N]");
odp = Console.ReadLine();
if (reply == "y" || reply == "Y")
break;
}
Console.WriteLine("The end loop");
With the help of the word break, we can break the loop, the matter is simple if we enter a letter other than y or Y in the console the same query will pop out and if we enter any of these two letters then we will exit from the loop.
The do-while loop differs in that the condition in the loop is executed first, then the condition is checked if the true one comes out of the loop if not then it will come back to the beginning.
There is no such C or C ++ loop, it is used to display an array or collection (collections and arrays will be later), however, it can not change the values that it displays and can not go outside the scope of the array in the for loop we need to take care of that. Example below:
int[] table = { 1, 2, 3, 4, 5 };
foreach (int a in table)
Console.WriteLine(a);
This code simply displays all values from the array named “array” I should give a line after the foreach loop in brackets, but if there is only one line, then you do not have to write it.
This content also you can find on my blog http://devman.pl/csharplan/c-language-4-loops/
If you recognise it as useful, share it with others so that others can also use it.
Leave upvote and follow and wait for next articles :) .
That’s probably enough to see in the next lesson!