×

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

What is 2s Complement in C?

The complement of 2s in C is generated from the 1s in C. As we know, the 1s complement of a binary number is generated by converting bit 1 to...

4 minutes read.

Pointers in C

Pointers in C: In the C programming language, a pointer is a pointer variable that points to the address of the other variable. It also stores the address of the...

4 minutes read.

Hook() function in C

Use of hook () function in C Introduction:  The hook () is a function used in the C programming language. The basic concept of the hook() function is that it can remove the function...

3 minutes read.

Beep() function in C

Introduction: Beep is a function which is used in C programming language. The beep function uses to make a beep sound. In the C language, when we want to generate...

3 minutes read.

C Language Environment Setup

To compile C program, we must have GCC compiler installed on our machine. In this C tutorial, all the examples are compiled and tested using GCC compiler. Although we can...

3 minutes read.

Passing Array to Function in C

Need to pass Arrays? The need to pass arrays to a function arises when we need to pass a list of values to a given function. During the course of our programming...

4 minutes read.

How to measure time taken by a function in C?

Measuring the time taken by a function is quite a complex task, because numerous methods are frequently not transferable to other platforms, measuring the execution time of a C programs...

5 minutes read.

Program to Find Mode of an Array in C

Mode is the highest occurring value or number in a given set of data elements. In a group of data values, a value that occurs most frequently is considered to...

3 minutes read.

Unformatted input() and output() function in C

Unformatted Input and Output functions take the character, character array, and strings as input. We can read-only character data types with these functions. These functions are already defined in the...

5 minutes read.

How to use atoi() function in C

Introduction: The atoi() is a function used in C programming language. This function converts string characters to the integer value. The atoi() function converts the input string to the return type of...

4 minutes read.

Modulus on Negative Numbers in C

In this tutorial, we will explore some examples of modulus on negative number. What is Modulus of Negative number? By omitting the minus sign, one can determine the modulus of a negative...

3 minutes read.

File Handling in C

File Handling is used to open, read, write, search and close file.  C files I/O functions handles data on secondary storage device. File handling function: There are varioushandling functions in C. Function Operation fopen() It is...

4 minutes read.

Pointer arithmetic in C

In the C programming language, a pointer is an address which stores a numeric value. Hence, a developer can perform several arithmetic operations on the same just as one does...

4 minutes read.

Fibonacci series in C

We have learned about the Fibonacci series in mathematics. For a quick recap, A Fibonacci series is the sequence of numbers following a certain pattern i.e., the next number should...

3 minutes read.

Use of Structure in C

We can usually use arrays in C programming to store elements of the same data type. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

File Operations in C

Why do I need the file? All data will be lost when the program exits. Saving data to a file keeps it safe even if the program stops working. If there...

6 minutes read.

Compound Interest Program in C

Interest on loans and deposits is compound interest. This is the most commonly used concept in everyday life. Compound interest on an amount is based on principal and interest earned...

3 minutes read.

CRC Program in C

CRC (Cyclic Redundancy Check) is an error-detection algorithm that is used to detect any errors that may have occurred during the transmission or storage of data. The basic idea behind...

4 minutes read.

Pi() Function in C

Pi: Mathematic constants are not defined in the c or c++ programming languages. To use the Mathematical constants firstly, we have to define the _USE_MATH_DEFINES and then declare the cmath and...

3 minutes read.

What is algorithm in C?

What is an algorithm? In computer programming languages, an algorithm is set of statement that solves a particular problem. In C, first step of every algorithm is Start and last step of...

3 minutes read.