Loops are here to help us when we need to repeat several lines of code. There are three types of loops. For loops, While loops, and a Do-While loop. We use a for loop when we want to a line of code to run a specific amount of times. For example, if I wanted to alert a line that states “Last Discussion Post” 5 times, I would do the following.
The for loop above alerts the line “Last Discussion Post” five times. We know this because i=0, which is us declaring what the value of i equals now. As long as i is less than or equal to five, which is what we did by writing “i<=5”, the code will run. Every time the code runs, i increases by one. We know this because we wrote “i++”. So, because of everything we declared, when this program is run, it will display “Last Discussion Post” five times.
When we don’t know the specific number of times to run a loop, we use a While loop. This loop will run a line of code until the statement within the loop is false.
Leave a Reply
You must be logged in to post a comment.