In this lesson, you will learn about for loops in C, their usage, and examples to better understand the topic.
A Loop is an Iterative Control Structure that includes several executions of the same lines of code
until a particular condition is fulfilled.” Loops are used as long as a specific requirement is encountered to perform the same block of code repeatedly. The fundamental concept behind a loop is to automate repetitive assignments within a program.
Three distinct loop kinds are supported by C:
In this lesson, we will focus on the For loops, and the Next lessons will cover the while and do-while loops.
The for loop loops thought a code block until a specific number of iterations is reached. It’s used widely in programming to loop thought lists of objects and Data Structures.
for (initialize; condition; increment){ //code to be processed here }
The flowchart below helps you understand the flow for the loop in C.
// Print the values from 1 to 5 #include <stdio.h> int main() { int var; for (var = 1; var <= 5; ++ var) { printf("%d\n", var); } return 0; }
Output
1 2 3 4 5
// Print the Table of 2 from 1 to 10 #include <stdio.h> int main() { int var, evennumber; printf ("C ***For loop*** Example\n"); printf (" -------For loop ---------\n"); printf ("The table of %d \n", 2); for (var = 1; var <= 10; var++) { //executes 10 times and increment evennumber = 2 * var; printf ("2 * %d is %d \n", var, evennumber); } return 0; }
Output
2 * 3 is 6 2 * 4 is 8 2 * 5 is 10 2 * 6 is 12 2 * 7 is 14 2 * 8 is 16 2 * 9 is 18 2 * 10 is 20
In Programming, you can use a loop inside another loop, which we call loop nesting. A nested for loop is fully executed for one outer loop in the case of an inner or nested loop. If the outer loop is to be executed four times and the inner loop three times, both loops will iterate 12 times ( 4 x 3)
// Print Nested For loop #include <stdio.h> int main () { int var, var2; printf ("C ***Nested For loop*** Example\n"); for (var = 1; var <= 4; var++) { //executes 4 times and increment printf ("Outer Loop %d times \n", var); for (var2 = 1; var2 <= 3; var2++) { //executes 3 times and increment printf ("Inner Loop %d times \n", var2); } printf ("\n"); } return 0; }
Output
C ***Nested For loop*** Example Outer Loop 1 times Inner Loop 1 times Inner Loop 2 times Inner Loop 3 times Outer Loop 2 times Inner Loop 1 times Inner Loop 2 times Inner Loop 3 times Outer Loop 3 times Inner Loop 1 times Inner Loop 2 times Inner Loop 3 times Outer Loop 4 times Inner Loop 1 times Inner Loop 2 times Inner Loop 3 times
In the next lesson, you will learn about another type of loop in C, the while loop.