For Loop
suggest changeA for loop repeats work a fixed number of times. The initializer, condition, and iterator sit in the header.
A for loop is set up like this:
for (Initialization; Condition; Increment)
{
// Code
}
-
Initialization: runs once. A variable declared here is scoped to the loop.
-
Condition: the body runs only while this is true. It is checked before each iteration.
-
Increment: runs after each iteration.
An example:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
Output:
0 1 2 3 4
Any of the three header sections may be empty, but both semicolons are required. input + 2 would not update input; the iterator has to assign it. Console.ReadLine returns a string, so parse it before comparing with an int.
int input = int.Parse(Console.ReadLine());
for (; input < 10; input += 2)
{
Console.WriteLine(input);
}
Output for 3. After 9 is printed, input becomes 11 and the condition fails, so 11 is not printed:
3 5 7 9
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents