- Control falls into the For Loop. Initialization is done.
- The flow jumps to the Condition.
- The Condition is tested.
- If it is true, the flow goes into the body.
- If it is false, the flow goes outside the loop.
- The statements inside the body of the loop get executed.
- The update takes place, and the flow goes to Step 3 again.
- The For Loop has ended, and the flow has gone outside.
Say we want to loop over a range of numbers and print out each one along the way. We can do this best with a For Loop. We will start from the first number, print it out, move to the next number to do the same thing, and continue until we’ve printed each number. Let’s print the numbers zero through nine:
Let’s look at the first line of the For Loop and the three parts necessary to make it work. First, we have an initialization expression, then termination expression, and increment expression in the end. The initialization expression initializes the loop and is only executed once when the loop starts. That is where you must declare and initialize a variable, usually of type int, to hold an initial number that will be used to loop until it reaches a specific value. That can be thought of as the start of the range to iterate over. In our case, we started at 0. The For Loop will continue looping until the termination expression evaluates to false. The termination expression is evaluated before each iteration of the loop, and it must return a boolean to decide whether or not to continue looping. If the boolean returned is equal to true, we will run the body of our For Loop again. In our case, the loop terminates after it prints 9. The increment expression is executed after each iteration of the loop. To increment the variable, we initialize it by using the ++ operator. That allows the termination expression to know how many times the loop loops. The initialization variable count, in our example, starts at 0, and it’s printed out. Then the incrementer increments it, and the next iteration of the loop runs to print the new value and continues that way until it prints 9. In conclusion, you should use a For Loop when you know how many times the loop should run. There are other more advanced iteration structures that we will look at in the next article.
- Increment adn Decrement
- For Loops
- Loops with a Step
- Iterating over Characters
- Infinite Loops
Remember that coding is a skill, which should be practiced. To learn to code, you should write code every day for a long time. Watching tutorials is not enough. You should code!
We would love to hear from you, so leave a comment below saying what topics you would like to see next.
Register now and take your free resources right away! You will get access to automated exercises which will sharpen your coding skills. You will become a member of the SoftUni Global Community and we will provide you the opportunity to communicate with other students and mentors and get help for FREE.