- Home /
c# loop why
why c# loop count till 9 if the condition say 10 ? even if the variable is 1
int i=0;
void start ()
{
while(i < 10)
{
Debug.Log(i);
i++;
}
}
p.s and i need to know what have this to do with games ?
for p.s games are basicly conditions and outcomes. you shoot, if the ball passes a rectangle, then it's a goal. in hide and seek, you hide while you are not seen by the seeker. in 8 ball, you lose if you pot the 8 ball while you have other balls left.
Answer by FrancisDuranceau · Apr 03, 2014 at 04:25 PM
When i == 10, you check the condition if i is less than 10, obviously it's equal and not less so you are done looping.
so , with the condition being i<10 im telling that the number must be smaller than 10 ,like 9 ?
Right, the way the while loop works is this:
First, it checks to see if i is less than 10. When the program starts, you set i to 0, so yes, zero is less than ten.
Then, the code says write to the log (`Debug.Log(i);`) and then add one to i (`i++;`) (so now i is equal to 1)
Now, because it's a while loop, it goes back and checks the condition again. "Is i less than 10?" -yes, 1 is less than 10
and it does the inside code again.
...
eventually i=9, the code says "Is i less than 10?" -yes 9 is less than 10
write to the log, add 1 to i. i is now 10.
the code asks again "Is i less than 10? ***-NO. 10 is not less than 10."
so then it moves past the while loop
Answer by wijesijp · Apr 03, 2014 at 04:26 PM
int i = 0;
void start()
{
while (i <= 10)
{
Debug.Log(i);
i++;
}
}
I provide a valid and correct answer. When I started answering it there were no replies. FrancisDuranceau beat me to it.
But why would anyone -1 this?
I took users code, fixed his error, post the answer I expected the user to compare his code with $$anonymous$$e and figure out what he has done wrong.
Worthwhile input is really subjective
i was asking why the number stop on 9 ,when my condition is 10
my int was 0 ,so i tought the loop count 10 times , since the
condition was (i < 10 times) XD
0 = 1
1 = 2
2 = 3
3 = 4
4 = 5
5 = 6
6 = 7
7 = 8
8 = 9
9 = 10
even if my variable is 1 it stops on 9 ,so in theory the loop
count 9 time ins$$anonymous$$d of 10 times
like this
1 = 1
2 = 2
3 = 3
4 = 4
5 = 5
6 = 6
7 = 7
8 = 8
9 = 9
because i was sure that the condition is a iteretion
i hope you understand what i mean :) because English is not my main language :)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
I dont know why im getting a null reference exception 1 Answer
Executing coroutines consecutively 0 Answers