C++ Loops
-
What is loop
Loop is code that is repeated until a certain condition is reached.
-
Control Flow statements
continue
Skips to next iteration of loopbreak
Goes out of a loop and breaks itreturn
Exits a function
-
Types of loops
There are four types of loops:
for
loop,for each
loop,while
loop anddo while
loop-
For loop
For loop is a loop that loops through code a (often i) number of times. In parameters we give ( statement 1; statement 2;
statement 3).
Statement 1 is often a setting variable before the loop starts called iterator that will be used in condition for the loop.
Statement 2 is condition for the loop to run. If condition is true the loop will start over again, else the loop will end.
Statement 3 is something that happens each time code block in the loop is executed often it is incrementing(adding) or decrementing
(subtracting) variable by some value.// iterator; condition; increment/decrement for(int i = 0; i < 10; i++){ // starting from 0 to i < 10 that will be 9 times loop // i++ means i = i + 1 or i+=1, we are adding 1 to i each time // some code here }
-
For each loop
For each loop is used to loop through elements of an array or other data sets.for(type variablename : arrayName){ // some code here }
-
While loop
While loop is loop that loops through code as long as specified condition is reached. It firstly checks the condition and then runs code.while(condtion){ // do some code }
-
Do while loop
Do While loop is loop that loops through code as long as specified condition is reached. Like in while loop but It firstly runs code and then it checks condition. Do while loop runs at least once no matter of the condition is true or false.do{ // do some code } while(condition);
-