[edit] C# for Loops
A for loop is a much better way to loop through statements then the previous techniques. using the goto statement breaks the flow of the program and can get very confusing when nesting goto loops. The for loop loops a certain number of times which is defined in the for loop declaration.
A for loop has its own internal counting system but the programmer must declare and initialize the loop variables.
for(<initialization>; <condition>; <increment>)
{
//code to loop through
}
Lets try this in real code:
using System; class Program { static void Main(string[] args) { for (int x = 0; x <= 10; ++x) { Console.WriteLine(x); } Console.Read(); } }
Line 7: This line is where the the counting operations take place.
- int x = 0 is where x is initialized
- x <= 10 says continue to loop while x is smaller than or equal to 10. If this statement were absent the loop would never stop.
- ++x is equivilant to x = x + 1. It simply increments x by 1.
Loops that are used to count from 0 to 10 you should use x <= 10 because x < 10 produces an "off by one error". Instead of counting from 0 to 10, x < 10 will count from 0 to 9.
Question:
what is (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15)
Before we give you the answer try solving this yourself.
Answer:
using System;
class Program
{
static void Main(string[] args)
{
int sum = 0;
for (int x = 0; x <= 15; ++x)
{
sum += x; //Equivalent to sum = sum + x
}
Console.WriteLine(sum);
Console.Read();
}
}
Output:
|