×

Nested loop in C

Definition of Nested Loop

A nested loop is generally used when we want to run a loop statement inside another loop statement. This kind of loop is also known as a “loop inside the loop”.

Diagrammatical presentation of Nested loop Code with the help of flow chart 

Nested loop in C

Explanation of the above Flow chart:

  1. As you can see, firstly, we provide an initialization statement.
  2. Then, the control evaluates the value of the first condition and checks whether the termination condition is true or false.
  3. If the value is false, the control will terminate the entire loop and only perform the basic command. But, if the value is true, it will continue to check the second condition.
  4. If it finds that the second condition is false, it will terminate the code of the second condition, and the control will move to the primary command and perform the loop. And if the value of the second condition is true, it will execute the code and check the termination condition, and it will continue to do so until the value becomes false.
  5. Along with this, some increment or decrement statements are also implemented after every statement execution.
  6. When the second condition terminates, the control goes back to the first condition, checks again, and repeats the entire execution process.
  7. The control will check and execute the termination condition multiple times.
  8. And it performs the condition given at the end and produces the output for displaying on the screen.

Now, let’s see the syntax of the nested loop in all loops of C.

Syntax Used For Initiating “Nested For Loop”:

for (initialization; termination condition; increment/decrement statement) {
      // program line of the first loop
   }
   // program line of the second loop
}

Syntax Used for Initiating “Nested While Loop”:

while(condition) 
{
// condition must be provided 
   while(condition) 
   { 
      // program line of the first loop
   }
   // program line of the second loop
}

Syntax Used for Initiating “Nested Do-While Loop”:

do
{
   do
   {     
      // program line of the first loop
   }
while(condition); //condition is given here
   // program line of the second loop
}
while(condition);

Syntax Used for Initiating “Nested Mixed (Do-While, While, For) Loop”:

do
{ while(condition) // condition should be provided
{   
 for (initialization; termination condition; increment/decrement condition) 
{  // program line of the first loop
 }
  // program line of the first while loop
 }
 // program line of second do-while loop
}
while(condition);

Example 01: Program of Nested for loop:

#include <stdio.h>
#include <stdlib.h> /* it involves memory 
  allocation, process control, conversions */
#define ROW 3 // rows declaration
#define COL 3 // columns declaration
// Driver program code
int main ()
{
    int i, j;
    // Declaration of the matrix
    int matrix [ROW][COL] = 
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19} 
};
        printf("the provided matrix is \n");
        // loops implementation
        for (i = 0; i < ROW; i++) // increment statement
   {
        for (j = 0; j < COL; j++) // increment statement
            printf("%d ", matrix[i][j]);
            printf("\n");
   }
    return 0;
}

Output:

the provided matrix is 
11 12 13 
14 15 16 
17 18 19 

Example 02: Program of nested while with for loop:

/* program in c to find out every prime factor
of a specific number with the help of nested loop */
#include <math.h> // library to include mathematical operations 
#include <stdio.h> 
// program line to display every possible prime factor of a provided number n
void prime factors (int n)
{
   // divisibility check 
   while (n % 2 == 0) 
   {
      printf("%d ", 2);
      n = n / 2;	
   }
   /* n must be odd So that one element can be we can be skipped
    (Note: i = i +2) */
   for (int i = 3; i <= sqrt(n); i = i + 2) 
   {
      // when n is divisible by i then display i and divide n
      while (n % i == 0) {
         printf("%d ", i);
         n = n / i;
      }
   }
   /* This test expression is defined to deal with the cases like 
    n is a prime number greater than 2 */
   if (n > 2)
      printf("%d ", n);
}
int main ()
{
   int n = 1578;
   primeFactors(n);
   return 0;
}

Output:

2 3 263

Related Topics

Typedef vs define in C

Typedef VS define in C Typedef In the C programming language, a keyword called typedef can be used to give a type a new name. In other words, it is used to...

5 minutes read.

Math functions in C

Math functions in C: In the C programming language, the compiler allows the developer to perform mathematical operations through the header’s functions, represented by <math.h>. The <math.h> header defines various mathematical...

3 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

Pure Virtual Function in C

Before knowing about the pure virtual function some of the important points about the virtual function in C++ are given below. In c++ the member function that is defined in the...

4 minutes read.

One Dimensional Array in C

One Dimensional Array in C: In the C programming language, an array is defined as a collection of one or more values of the same type. Every value present in...

4 minutes read.

Multithreading in C interview questions

Q1. What exactly is a thread? Ans: A thread is a brief sequence of instructions intended to be planned and carried out by the CPU apart from the parent process. Q2. Can...

4 minutes read.

FIFO Example in the C Language

FIFO is an acronym that means "First In, First Out." It is a data structure handling method in which the first element is handled first, and the last element is...

3 minutes read.

Difference between Array and List in C

C# Array vs List is where the abstraction and implementation of human computing meet.  Arrays are incredibly related to the hardware concept of contiguous and contiguous memory, where each part is...

3 minutes read.

Factorial Program in C using For Loop

Before move on the factorial program. We have to know about the for loop in C programming language. The syntax of the For Loop is: for (initialization statement; test expression; an increment...

3 minutes read.

Stack implementation in C

Stack implementation in C Stack stores the data in a particular order. It is a linear data structure that follows the principle of the Last In First Out (LIFO) technique where...

3 minutes read.

Prime Number Program in C using for Loop

In this article, we will know about the procedure of checking whether a natural number inputted by the user is a prime number or non-prime number. Definition of the prime number A...

3 minutes read.

Diffie-Hellman Algorithm in C

Background: A method of public-key encryption known as elliptic curve cryptography (ECC) is based on the algebraic structure of elliptic curves over finite fields. To ensure equal security, ECC encryption requires fewer...

4 minutes read.

String literals in C

Constants refer to the fixed values of the program that may not alter during the compiling ad execution. These fixed values are known as literals. In other words, the values...

3 minutes read.

First Fit Program in C

This is one of the easiest ways to allocate memory. The main goal is to divide the memory into several fixed sizes. In C, there is only one process for...

3 minutes read.

C program that does not Suspend when Ctrl+Z is Pressed

In Programming when a program breakdown and runs surprisingly in the terminal compiler the developer has the ability to prevent the program from running unequivocally. For expressly halting the program,...

3 minutes read.

How to open a C file on android mobile

A C file is a file that has a .c extension and contains code written in the C language. C is a computer programming language developed by Dennis Ritchie at...

4 minutes read.

Fee Management System in C

The concept is to split every operation into its very own characteristic. Software is made from all of the capabilities mixed with transfer cases. An example of the capabilities may...

5 minutes read.

Explain the Increment and Decrement Operators in C

In the C programming language, the increment operator (++) and the decrement operator (--) are used to increase or decreasing a variable’s value by 1, respectively. The increment operator is written...

10 minutes read.

Infinite loop in C

Definition of infinite loop The infinite loop is a loop that does not get dismissed because of its looping construct. A continuous output or no output are the two possible outcomes...

3 minutes read.

Star Program in C Language

Star Program in C Star patterns are a sequence of * or any other character used to construct any pattern or any like-square geometric form, triangle, hollow square, pyramid, rhombus, etc.  Many programmers worldwide highly...

4 minutes read.