C Nested For

Guidance of nested 'for' loops in C.

Nested For Loops:

A nested 'for' loop in C is a loop inside another loop. This is a common technique used when you need to perform repeated operations within repeated operations. The outer loop controls the number of iterations, and the inner loop performs its iterations for each iteration of the outer loop. Here's the basic syntax of a nested 'for' loop in C:

for (outer_initialization; outer_condition; outer_increment/decrement) {
    // Code before the inner loop
    
    for (inner_initialization; inner_condition; inner_increment/decrement) {
        // Code to be executed repeatedly within the inner loop
    }
    
    // Code after the inner loop
}

You can nest 'for' loops to create various patterns and perform complex operations. Here's an example of a nested 'for' loop to print a multiplication table:

c Copy Code
#include <stdio.h>

int main()
{
    int i, j;

    for (i = 1; i <= 5; i++) // Outer For Loop
    {

        for (j = 1; j <= 10; j++) // Inner For Loop
        {
            printf("%d * %d = %d\n", i, j, i * j);
        }

        printf("\n"); // For new line
    }

    return 0;
}

Explanation:

  • The outer loop (controlled by 'i') runs from 1 to 5.
  • The inner loop (controlled by 'j') runs from 1 to 10 for each value of 'i'.
  • Inside the inner loop, we print the product of 'i' and 'j', which results in a multiplication table.
Output:
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30

4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36
4 * 10 = 40

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

Note: Nested 'for' loops are versatile and can be used for various tasks that involve multiple levels of iteration.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.