[edit] C# Simple Loops
We will discuss loops in this section and looping techniques
looping is very necessary because it relieves the programmer from time consuming tasks. Developers are able to execute statements repeatedly millions of times if they need to. Tedious calculations can also benefit from loops as well. Lets see how loops can make our job easier.
Lets print the numbers from 1 to 10
Example 1:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(1);
Console.WriteLine(2);
Console.WriteLine(3);
Console.WriteLine(4);
Console.WriteLine(5);
Console.WriteLine(6);
Console.WriteLine(7);
Console.WriteLine(8);
Console.WriteLine(9);
Console.WriteLine(10);
Console.Read();
}
}
Output
A grueling way to print from 1 to 10. Lets examine a more efficient way to do basic counting using goto.
Example 2
using System;
class Program
{
static void Main(string[] args)
{
int x = 0;
LoopLabel:
x += 1; //Equivalent to x = x + 1
Console.WriteLine(x);
if (x < 10) //if x is less than 10 then goto LoopLabel
goto LoopLabel;
Console.Read();
}
}
Output:
This is a much more efficient way to count from 1 to 10 or even a thousand or 1 million
|