Loops are used to repeatedly execute a block of code as long as a specified condition is true. In C, there are three main types of loops:
The for loop is used when the number of iterations is known beforehand. It includes three parts: initialization, condition, and increment/decrement.
for (initialization; condition; increment/decrement) { // Code to be executed }
#includeint main() { for (int i = 1; i <= 5; i++) { printf("%d\n", i); } return 0; }
The while loop is used when the number of iterations is not known in advance, but the loop should continue as long as a condition remains true.
while (condition) { // Code to be executed }
#includeint main() { int i = 1; while (i <= 5) { printf("%d\n", i); i++; } return 0; }
The do-while loop is similar to the while loop, but the condition is checked after the code is executed. This ensures that the loop is always executed at least once.
do { // Code to be executed } while (condition);
#includeint main() { int i = 1; do { printf("%d\n", i); i++; } while (i <= 5); return 0; }
break
or continue
statements to control loop flow in certain situations.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!