For loop is another way of repeating code.
for( initial; condition; step){
//run some code
}
As you see, for loop includes three part:
1. The first part is the initialize where we declare a variable and set it to some initial value.
2. The second part is condition which is when this loop should keep running.
3. The last part is step, so what do we do at the end of every iteration.
I would like to share two examples from the course:
Print numbers from 0 to 5 with a for loop
I write the for loop in the console. There are three part in the for loop:
1. Initial: count start from 0 (count = 0)
2. Condition: run the code until the count is less than 6 ( count < 6)
3. Step: count incrementally
The result list 0 to 5.
Print each character in a string with a for loop
1. Initial: list the character from the beginning (start 0)
2. Condition: run the code until it end by the string length
3. Step: list all the characters in order
The result list each character for “hello”
网友评论