I have an question regarding for loops in C#.
My code:
for(i = 1; i < 100; i*=2)
{
Console.Write(i + " ");
}
Console.Readkey();
I think that the result should be "2 4 8 16 32 64" but I get "1 2 4 8 16 32 64". Where did "1" come from?
I have an question regarding for loops in C#.
My code:
for(i = 1; i < 100; i*=2)
{
Console.Write(i + " ");
}
Console.Readkey();
I think that the result should be "2 4 8 16 32 64" but I get "1 2 4 8 16 32 64". Where did "1" come from?
You are initializing i as 1 with i=1, which is where the 1 comes from.
The increment (your i*=; portion) doesn't get called until the loop has completed at least once, so it doesn't get to the next value until after it displays the value of i, which is 1
To see what you're expecting, you need to change the loop to:
for(i = 2; i < 100; i*=2)
{
Console.Write(i + " ");
}
Console.Readkey();
I know you already get your correct answer but I want to explain more deep because I assume you are a beginner programmer.
From $8.8.3
The for statement in C# spec;
for-statement:
for ( for-initializer ; for-condition ; for-iterator ) embedded-statement
A for statement is executed as follows:
- If a for-initializer is present, the variable initializers or statement expressions are executed in the order they are written. This step is only performed once.
- If a for-condition is present, it is evaluated.
- If the for-condition is not present or if the evaluation yields true, control is transferred to the embedded statement. When and if control reaches the end point of the embedded statement (possibly from execution of a continue statement), the expressions of the for-iterator, if any, are evaluated in sequence, and then another iteration is performed, starting with evaluation of the for-condition in the step above.
- If the for-condition is present and the evaluation yields false, control is transferred to the end point of the for statement.
As you can see, for-iterator (which is i*=2
in your case) will not executed until you complete the first iteration since since i < 100
returns true
for i = 1
.
Since a picture is worth a thousand words, so..
You are starting with i=1 therefore your first number is 1.
The for loop is made of three elements : start , condition and step.
I will try to explain few steps so you can get the idea.
First you go in with 1, you print it. Then it gets to i*=2 which is the equivalent of i=i*2.After this the condition is verified, if it is true then proceed to the execution block again. Hope this cleared it up for you. Also you are just multiplying by 2, not raising at the power of 2, which is explained in another answer.
You should use
for(i = 2; i <= 100; i=i*2)
{
Console.Write(i + " ");
}
Console.Readkey();