3.0 For loop #
Created Tuesday 22 October 2019 structure of a for loop: init variable(s) while(check_condition){
incerement/decrement; }
structure for the for loop: for(init; condition_check; increment){
} for and while are exactly the same, except jargon. Advantages of a for loop:
- We tend to forget the increment condition, this helps in avoiding the mistake.
- It makes the code neater.
Important:
- All the three parts of the for are optional, we can skip one or more of them. But the three semicolons are **compulsory. **http://www.cplusplus.com/doc/tutorial/control/
- In the initialization, we can initialize multiple variables, separated by commas. It’s(first expression’s) value does not matter anyway.
- In the check_condition, all boolean expressions have to be connected using bool operators only, no commas should be used.
- the increment part can have multiple increment parts separated by commas.
Running time:
- the inititializer is run only 1 time
- the checker is run n times, this including the anchor/stopping condition.
- the incrementer runs n times, including the last increment.
State: The start state is the initializer. The end state is the checker or a break inside the body.
**A hard lesson: The order of content in a loop does matter. **
- Read only about for and while loop: