Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
Nested Structure in C with Examples
Next article icon

Nested Loops in C with Examples

Last Updated : 25 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

A nested loop means a loop statement inside another loop statement. That is why nested loops are also called “loop inside loops“. We can define any number of loops inside another loop.

1. Nested for Loop

Nested for loop refers to any type of loop that is defined inside a ‘for’ loop. Below is the equivalent flow diagram for nested ‘for’ loops:

Nested for loop in C

Nested for loop in C

Syntax:

for ( initialization; condition; increment ) {       for ( initialization; condition; increment ) {                // statement of inside loop     }       // statement of outer loop  }

Example: Below program uses a nested for loop to print a 3D matrix of 2x3x2.

C




// C program to print elements of Three-Dimensional Array
// with the help of nested for loop
#include <stdio.h>
  
int main()
{
    // initializing the 3-D array
    int arr[2][3][2]
        = { { { 0, 6 }, { 1, 7 }, { 2, 8 } },
            { { 3, 9 }, { 4, 10 }, { 5, 11 } } };
  
    // Printing values of 3-D array
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 2; ++k) {
                printf("Element at arr[%i][%i][%i] = %d\n",
                       i, j, k, arr[i][j][k]);
            }
        }
    }
    return 0;
}
 
 
Output
Element at arr[0][0][0] = 0  Element at arr[0][0][1] = 6  Element at arr[0][1][0] = 1  Element at arr[0][1][1] = 7  Element at arr[0][2][0] = 2  Element at arr[0][2][1] = 8  Element at arr[1][0][0] = 3  Element at arr[1][0][1] = 9  Element at arr[1][1][0] = 4  Element at arr[1][1][1] = 10  Element at arr[1][2][0] = 5  Element at arr[1][2][1] = 11

2. Nested while Loop

A nested while loop refers to any type of loop that is defined inside a ‘while’ loop. Below is the equivalent flow diagram for nested ‘while’ loops:

Nested while loop in C

Nested while loop in C

Syntax:

while(condition) {       while(condition) {                // statement of inside loop     }       // statement of outer loop  }

Example: Print Pattern using nested while loops

C




// C program to print pattern using nested while loops
#include <stdio.h>
  
int main()
{
    int end = 5;
  
    printf("Pattern Printing using Nested While loop");
  
    int i = 1;
  
    while (i <= end) {
        printf("\n");
        int j = 1;
        while (j <= i) {
            printf("%d ", j);
            j = j + 1;
        }
        i = i + 1;
    }
    return 0;
}
 
 
Output
Pattern Printing using Nested While loop  1   1 2   1 2 3   1 2 3 4   1 2 3 4 5 

3. Nested do-while Loop

A nested do-while loop refers to any type of loop that is defined inside a do-while loop. Below is the equivalent flow diagram for nested ‘do-while’ loops:

nested do while loop in C

do while loop in C

Syntax:

do{       do{                // statement of inside loop     }while(condition);       // statement of outer loop  }while(condition);

Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level.

Syntax:

do{       while(condition) {                for ( initialization; condition; increment ) {                   // statement of inside for loop        }          // statement of inside while loop     }       // statement of outer do-while loop  }while(condition);

Example: Below program uses a nested for loop to print all prime factors of a number. 

C




// C Program to print all prime factors
// of a number using nested loop
  
#include <math.h>
#include <stdio.h>
  
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
    // Print the number of 2s that divide n
    while (n % 2 == 0) {
        printf("%d ", 2);
        n = n / 2;
    }
  
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2) {
        // While i divides n, print i and divide n
        while (n % i == 0) {
            printf("%d ", i);
            n = n / i;
        }
    }
  
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        printf("%d ", n);
}
  
/* Driver program to test above function */
int main()
{
    int n = 315;
    primeFactors(n);
    return 0;
}
 
 
Output:
3 3 5 7

Break Inside Nested Loops

Whenever we use a break statement inside the nested loops it breaks the innermost loop and program control is inside the outer loop. 

Example: 

C




// C program to show working of break statement
// inside nested for loops
#include <stdio.h>
  
int main()
{
  
    int i = 0;
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 3; j++) {
            // This inner loop will break when i==3
            if (i == 3) {
                break;
            }
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}
 
 
Output
* * *   * * *   * * *     * * * 

In the above program, the first loop will iterate from 0 to 5 but here if i will be equal to 3 it will break and will not print the * as shown in the output. 

Continue Inside Nested loops

Whenever we use a continue statement inside the nested loops it skips the iteration of the innermost loop only. The outer loop remains unaffected.

Example:

C




// C program to show working of continue statement
// inside nested for loops
#include <stdio.h>
  
int main()
{
  
    int i = 0;
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 3; j++) {
            // This inner loop will skip when j==2
            if (j==2) {
                continue;
            }
            printf("%d ",j);
        }
        printf("\n");
    }
    return 0;
}
 
 

In the above program, the inner loop will be skipped when j will be equal to 2. The outer loop will remain unaffected.



Next Article
Nested Structure in C with Examples

C

code_r
Improve
Article Tags :
  • C Language
  • C-Loops & Control Statements

Similar Reads

  • Nested Structure in C with Examples
    Pre-requisite: Structures in C A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure. Syntax: struct name_1{ member1; member2; . . membern; struct name_2 { member_1; member_2;
    9 min read
  • do...while Loop in C
    The do...while loop is a type of loop in C that executes a block of code until the given condition is satisfied. The feature of do while loops is that unlike the while loop, which checks the condition before executing the loop, the do...while loop ensures that the code inside the loop is executed at
    4 min read
  • while Loop in C
    The while loop in C allows a block of code to be executed repeatedly as long as a given condition remains true. It is often used when we want to repeat a block of code till some condition is satisfied. Let's take a look at an example: [GFGTABS] C #include <stdio.h> int main() { int i = 1; // C
    5 min read
  • Jagged Array or Array of Arrays in C with Examples
    Prerequisite: Arrays in CJagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Example: arr[][] = { {0, 1, 2}, {6, 4}, {1, 7, 6, 8, 9}
    3 min read
  • Using Range in switch Case in C
    You all are familiar with switch case in C, but did you know you can use a range of numbers instead of a single number or character in the case statement? Range in switch case can be useful when we want to run the same set of statements for a range of numbers so that we do not have to write cases se
    2 min read
  • Nested Functions in C
    Nesting of functions refers to placing the definition of the function inside another functions. In C programming, nested functions are not allowed. We can only define a function globally. Example: [GFGTABS] C #include <stdio.h> int main() { void fun(){ printf("GeeksForGeeks"); } fun(
    4 min read
  • Output of C programs | Set 30 (Switch Case)
    Prerequisite - Switch Case in C/C++ Interesting Problems of Switch statement in C/C++ Program 1 #include <stdio.h> int main() { int num = 2; switch (num + 2) { case 1: printf("Case 1: "); case 2: printf("Case 2: "); case 3: printf("Case 3: "); default: printf(
    2 min read
  • Nested printf (printf inside printf) in C
    Predict the output of the following C program with a printf inside printf. #include<stdio.h> int main() { int x = 1987; printf("%d", printf("%d", printf("%d", x))); return(0); } Output : 198741 Explanation : 1. Firstly, the innermost printf is executed which resul
    1 min read
  • Sequence Points in C | Set 1
    In this post, we will try to cover many ambiguous questions like following. Guess the output of following programs. // PROGRAM 1 #include <stdio.h> int f1() { printf ("Geeks"); return 1;} int f2() { printf ("forGeeks"); return 1;} int main() { int p = f1() + f2(); return 0;
    4 min read
  • Facts and Question related to Style of writing programs in C/C++
    Here are some questions related to Style of writing C programs: Question-1: Why i++ executes faster than i + 1 ? Answer-1: The expression i++ requires a single machine instruction such as INR to carry out the increment operation whereas, i + 1 requires more instructions to carry out this operation.
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences