Loops are very useful when you want to perform a task repeatedly. Loop’s body has set of statements, which gets executed on every iteration.
We have three types of loop control structures in C, even through working of these following loops are almost similar still there is a major difference among them. You may need to choose one based on the requirement.
Below are the tutorials for each type of loop (for, while, do-while) & loop control statements(break, continue, goto).
- for loop: This is most commonly used loop in C language. The syntax and flow of this loop is simple and easy to learn. However there are few cases when you may prefer any other loop, instead of this.
- while loop: This is used when you need to repeatedly execute the block of statements, for fixed number of times. Read this tutorial to understand the flow of this loop.
- do-While loop: It is similar to the while loop, the only difference is that it evaluates the test condition after execution of the statements enclosed in the loop body.
- break statement: It is used with various loops (for, while and do-While) and switch case statements. When compiler finds break inside loop, the control comes out of the loop and when when it gets encountered in switch-case, the flow comes out of the control structure and continue execution with the statement following switch-case body.
- continue statement: Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body for the current iteration.
- goto statement: When compiler encounters goto statement in a C program, the control jumps to the corresponding label mentioned along with goto. It is not used frequently as it makes the program complex and confusing.