Nested For Loop in C Programming
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Nested For Loop in C Programming – Syntax, Flowchart and Examples

šŸ“‘ On this page:
  • Introduction
  • What is a Nested For Loop?
  • Real-World Use Cases
  • Advantages of Nested For Loop
  • Disadvantages of Nested For Loop
  • Flowchart of Nested For Loop
  • Syntax of Nested For Loop
  • Multiplication Table Example
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • What is a nested for loop and why it is used in C programming
  • How nested for loop works with step-by-step flowchart explanation
  • Real-world use cases of nested for loops
  • How to write programs using nested for loop
  • Complete program example with explanation

Introduction

In this tutorial section, we will learn what a nested for loop is in the C programming language.

What is a Nested For Loop in C?

A nested for loop in C Programming refers to a for loop within the body of another for loop. There can be any number of loops nested within one another. Nested loops are fully supported by the C programming language.

šŸ’” Key Point: To create nested loops, we can nest multiple types of loops within one other. However, nested for loops are the most common type used in C programming.

Real-World Use Cases of Nested For Loop

  • ATM Machine Software: Uses loops to process transactions
  • Spell Checking: Checking each word against a dictionary
  • Email Reading: The process of reading all emails in your account when you log in
  • Multiplication Tables: Generating tables from 1 to 10
  • Matrix Operations: Traversing 2D arrays and matrices

Advantages of Using Nested For Loop in C Programming

1. Multi-dimensional data traversal — Used to iterate through multi-dimensional data structures like arrays and matrices

2. Better code readability — Makes code more readable, structured, and easy to understand

3. Complex operations — Used to perform complex operations that involve nested iteration

4. Pattern printing — Useful for printing patterns, pyramids, and shapes

Disadvantages of Using Nested For Loop in C Programming

1. Time Complexity: Performance and complexity can be reduced by using more efficient data structures. They can result in poor performance on large datasets as the number of iterations increases at each level of nesting.

2. Harder to debug: Nested for loops are more difficult to understand and debug, especially for beginners.

3. Increased complexity: With each level of nesting, the code becomes more complex and harder to maintain.

Flowchart of Nested For Loop

The diagram below shows the step-by-step control flow of a nested for loop in C programming.

Flowchart of nested for loop in C language showing execution flow

Let's understand how nested for loops work step by step:

1. Initialize-for-1: This is the first section or statement in the outer for loop. It allows the programmer to declare and initialize the variables that can be used inside the test condition, inside the body of the loop, or in the update expression. Initialize-for-1 executes only once for n iterations of the loop. Next, control jumps to the test expression i.e., "is condition-for-1 valid?"

2. Is condition-for-1 valid?: This is the second statement in the outer for loop which tests the condition. The test condition may be true or false depending on the validation of the test condition. When condition-for-1 evaluates to "false", the control cannot enter the inner for loop and stops the entire execution of the nested for loop. When condition-for-1 evaluates to "true", the control jumps inside the inner for loop and starts "initialize-for-2".

3. Initialize-for-2: This is the first statement inside the inner for loop. The working of this statement is the same as the outer for loop's "initialize-for-1" statement. After execution of "initialize-for-2", the control jumps to test the condition "is condition-for-2 valid?"

4. Is condition-for-2 valid?: This is the second statement in the inner or nested for loop which tests the condition. The test condition may be true or false depending on the validation of the test condition. When condition-for-2 evaluates to "true", the control enters inside the inner loop and starts executing "Execute statements inside 2nd for loop". These statements are also known as the body of the loop. After successful execution of the statements, the control starts executing "update-for-2".

5. Update-for-2: This is the update expression or iteration expression in the inner for loop. It executes after the execution of the loop body or at the end of each iteration. This is one of the important statements in a for loop that increments the loop counter variable. After successful execution of update-for-2, the control jumps back to test the condition in step 4 and continues execution of the inner loop until "is-condition-for-2 valid?" is false. Otherwise, control jumps or exits out of the inner loop and executes "update-for-1".

6. Update-for-1: This is the update expression or iteration expression in the outer for loop. It executes after the execution of the loop body of the first loop or at the end of each iteration. After successful execution of update-for-1, the control jumps back to test the condition in step 2 and continues execution of the outer loop until "is-condition-for-1 valid?" is true; otherwise, it stops the execution.

Syntax of Nested For Loop in C

Let us study the syntax of a nested for loop and then we will look in detail into all parts of the nested for loop.

/* statements outside loop */
for(initialize-for-1; condition-for-1; update-for-1) {
    /* second for loop */
    for(initialize-for-2; condition-for-2; update-for-2) {
        /* Executes the Statements inside 2nd for loop */
    }
}
/* statement outside loop */

Let's break down each part:

šŸ”¹ Outer For Loop: The control enters the outer for loop and executes the statement initialize-for-1. Then it tests the condition condition-for-1. If true, it enters the body of the outer loop.

šŸ”¹ Inner For Loop: Inside the outer loop body, the control enters the inner for loop. It executes initialize-for-2, then tests condition-for-2. If true, it executes the statements inside the inner loop.

šŸ”¹ Update Expressions: After the inner loop body executes, update-for-2 runs and the condition is rechecked. This continues until the inner condition becomes false. Then update-for-1 runs and the outer condition is rechecked.

Nested for loop syntax in C Programming

C Program to Illustrate Nested For Loop

The program below displays the multiplication table from 1 to 10 using nested for loops.

#include <stdio.h>

int main() {
    int n, i;
    
    printf("\n Table from 1...10 Using Nested for loop\n");
    
    for(n = 1; n <= 10; n++) {
        for(i = 1; i <= 10; i++) {
            printf("\t %d", n * i);
        }
        printf("\n");
    }
    
    return 0;
}

Sample Output:

Table from 1...10 Using Nested for loop

1    2    3    4    5    6    7    8    9    10
2    4    6    8    10   12   14   16   18   20
3    6    9    12   15   18   21   24   27   30
4    8    12   16   20   24   28   32   36   40
5    10   15   20   25   30   35   40   45   50
6    12   18   24   30   36   42   48   54   60
7    14   21   28   35   42   49   56   63   70
8    16   24   32   40   48   56   64   72   80
9    18   27   36   45   54   63   72   81   90
10   20   30   40   50   60   70   80   90   100

Explanation:

  1. Variables int n, i; are declared.
  2. printf("\n Table from 1...10 Using Nested for loop"); displays the heading message on the console.
  3. The control enters the outer for loop: for(n = 1; n <= 10; n++)
    • n is initialized to 1.
    • The condition n <= 10 is checked. Since 1 <= 10 is true, control enters the body of the outer loop.
  4. Inside the outer loop, control enters the inner for loop: for(i = 1; i <= 10; i++)
    • i is initialized to 1.
    • The condition i <= 10 is checked. Since 1 <= 10 is true, control enters the inner loop body.
    • printf("\t %d", n * i); prints the product — in this case, 1 Ɨ 1 = 1.
    • i++ increases the value of i to 2.
    • The condition i <= 10 is checked again. Since it's still true, the loop continues and prints the next value.
    • This continues until i becomes 11, which makes the condition false.
  5. The inner loop ends, and control returns to the outer loop.
  6. printf("\n"); moves to the next line.
  7. n++ increases the value of n to 2.
  8. The outer loop checks n <= 10 again, and since it's true, it goes through the same process for n = 2.
  9. This continues until n becomes 11, which breaks the outer loop.
  10. As a result, we get the full multiplication table from 1 to 10 printed using nested for loops.

šŸ’» Practice Exercise

Challenge: Write a program using nested for loops to print the following pattern:

*
* *
* * *
* * * *
* * * * *
šŸ” Click to Show Solution
#include <stdio.h>

int main() {
    int i, j;
    
    for(i = 1; i <= 5; i++) {
        for(j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
    
    return 0;
}

šŸ“ Summary

  • A nested for loop is a for loop within another for loop
  • The inner loop completes all its iterations for each outer loop iteration
  • It is useful for processing multi-dimensional data like matrices and tables
  • Common real-world uses include: multiplication tables, pattern printing, and ATM processing
  • Proper initialization, update expressions, and loop conditions are necessary to avoid infinite loops

Frequently Asked Questions About Nested For Loop in C

1. What is a nested for loop in C?

A nested for loop is a for loop placed inside another for loop. The inner loop executes completely for each iteration of the outer loop.

2. When should I use a nested for loop?

Use nested for loops when you need to process data in multiple dimensions, such as matrices, tables, or when one loop's execution depends on another loop's iterations.

3. Can I nest more than two for loops?

Yes, you can nest as many for loops as needed. However, too many nested loops can make code hard to read and debug.

4. What is the time complexity of nested for loops?

The time complexity of nested for loops is O(n²) for two levels, O(n³) for three levels, and so on. This means performance decreases significantly as the number of nesting levels increases.

5. What is the difference between nested while and nested for loop?

The main difference is syntax. For loops are used when the number of iterations is known, while loops are used when the number of iterations is unknown. Both can be nested similarly.

šŸ’” Tip: When writing nested for loops, always make sure the inner loop's update expression eventually makes its condition false. Otherwise, you might create an infinite loop.

šŸ“– Related Tutorials

  • for Loop in C - Complete Guide
  • for Loop Examples in C
  • while Loop in C - Complete Guide
  • Introduction to Loops in C

Previous Topic: -->> for loop examples   ||   Next topic: -->> nested for loop examples


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.