Skip to main content

Nesting of Loops

We can write one loop inside another loop.A loop within another loop is called a nested loop.

In C programming, nested loops are loops that are placed inside another loop. This allows you to repeat a set of instructions multiple times, and inside each iteration of the outer loop, the inner loop completes its full iteration. Nested loops are useful when you need to perform repetitive tasks within repetitive tasks.

The following is the syntax of writing one for loop inside another for loop.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. Each inner (nested) loop must be completely embedded within an outer loop, the loops cannot overlap.Here for each iteration of the outer loop, the inner loop keep executing completely.
Nesting of for loop
for ( initialization; condition; increment ) 
    for ( initialization; condition; increment ) 
    { // statement of inside loop 
    
    // statement of outer loop
 }
Nesting of while loop
while (condition)
{
    while(condition)
     {
     } // inner loop
}//outer loop
we can also nest for loop inside while and also while inside for loop. The nesting can go to any level also.

Example:
#include <stdio.h>
int main()
{
    int i,j;
    for(i=0;i<5;i++)
    {
     for(j=0;j<10;j++)
       { 
           printf("* ");
       }
        printf("\n");
    }
}
Output:
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
Note: The outer loop executes 5 times.The inner loop executes 10 times and print 10 '*' each time.

Example:
#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}
Output:n=3
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

Explanation of the above code
First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
The program control checks whether the condition 'i<=n' is true or not.
If the condition is true, then the program control passes to the inner loop.
The inner loop will get executed until the condition is true.
After the execution of the inner loop, the control moves back to the update of the outer loop, i.e., i++.
After incrementing the value of the loop counter, the condition is checked again, i.e., i<=n.
If the condition is true, then the inner loop will be executed again.
This process will continue until the condition of the outer loop is true.

Example:
#include <stdio.h>

int main() {
    int i, j, k;

    // Outer loop controls the layers
    for (i = 1; i <= 3; i++) {

        // Middle loop controls the rows in each layer
        for (j = 1; j <= 3; j++) {

            // Inner loop controls the columns in each row
            for (k = 1; k <= 3; k++) {
                printf("* ");
            }

            // Move to the next line after each row is printed
            printf("\n");
        }

        // Separate each layer with a newline
        printf("\n");
    }

    return 0;
}
* * * 
* * * 
* * * 

* * * 
* * * 
* * * 

* * * 
* * * 
* * *

In this example, the outermost loop controls the layers, the middle loop controls the rows within each layer, and the innermost loop controls the columns within each row. The program prints a block of stars for each layer, with each block containing three rows and three columns.

Remember that the indentation in the code helps to visualize the structure of the nested loops. When working with nested loops, it's crucial to keep track of the loop indices and their ranges to achieve the desired pattern or behavior.
Example programs
#include <stdio.h>
main()
{
int i,j;
for(i=1;i<=5;i++)
{
    for(j=1;j<=i;j++)
    {
    printf("* ");
    }
printf("\n");
}
}
o/p
*
* *
* * *
* * * *
* * * * *
Here the inner for loop executes i times.when i=1 it execute 1 time and prints one *.when i=2 it executes 2 times and  it print *  * . The outer loop repeats 5 times.
 
program to print multiplication table of numbers from 2-10
#include <stdio.h>
main()

 
   int n,i;
     for(n=2;n<=10;n++)
     {
       printf("Multiplication table of %d\n",n);
      
      for(i=1;i<=15;i++)
         {printf("%2d * %2d = %2d\n",i,n,i*n);
         }
     
      }
}
Note: here the inner loop is used to print the multiplication table of a number upto 15 and the outer loop will select the number from 2 -10.
 
Factorial of each digit of a number
 
#include <stdio.h>
main()

   int i,n,f,dig;
   printf("Enter the number...:);
   scanf("%d",&n);
    while(n!=0)
     {
       dig=n%10;         
       n=n/10;
       f=1;
       for(i=2;i<=dig;i++)
              f=f*i;
       printf("%d-fact= %d\n",dig,f);

      }
   
}

Write a C Program to check if a given number is a strong number(Krishnamurti number) or not. A strong number is a number in which the sum of the factorial of the digits is equal to the number itself. 
Eg:- 145=1!+4!+5!=1+24+120=145 ( university question)
#include <stdio.h>
main()

   int i,n,f,dig,sum=0,t;
   printf("Enter the number:");
    scanf("%d",&n);
    t=n;
    while(n!=0)
     {
       dig=n%10;         
       n=n/10;
       f=1;
       for(i=2;i<=dig;i++)
              f=f*i;
       sum=sum+f;

      }
   if(t==sum)
     printf("Strong number\n");
    else
     printf("Not a Strong number\n");
     
}

Note:Nested loops are widely used for matrix processing( reading, printing, matrix arithmetic etc)

break and continue Inside Nested Loops

When we use a break statement inside the inner loop, it terminates the inner loop but not the outer loop.
Similarly, when we use a continue statement inside the inner loop, it skips the current iteration of the inner loop only. The outer loop is unaffected.

The following program will find out all prime numbers less than 100
#include <stdio.h>
 int main () 
{ /* local variable definition */
 int i, j; 
for(i = 2; i<100; i++) 
for(j = 2; j <= (i/j); j++) 
    {if(i%j==0) break;} // if factor found, not prime 
 if(j > (i/j)) printf("%d is prime\n", i); 
  } 
return 0; 
}

Programs to try using nested loops

Generate the following pattern
1)
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
2) 
* * * * *
* * * *
* * *
* *
*
3) 
1
2 3
4 5 6
7 8 9 10
4)Print the multiplication table of numbers from 5-15.
5)Print all prime numbers in a given range.
6)Print all 3 digit Armstrong numbers in a range.
7)Print all the factors of numbers between 10 and 20.
8)Print the factorial of each digit of the number.(use a for loop to find the factorial)
9)Print all Krishnamurti numbers in the given range.
10)Print the sum of digits of all numbers between 100 and 200.
11)Print all perfect numbers less than 1000.
12)Write a C Program to check if a given number is a strong number or not. A strong number is a number in which the sum of the factorial of the digits is equal to the number itself. 
Eg:- 145=1!+4!+5!=1+24+120=145 ( university question)
13)generate the following pyramid(develop a formula to generate the appropriate output for each line.)
                    1
                  232
                34543
              4567654
            567898765
           67890109876
        7890123210987
      890123454321098
     90123456765432109
    0123456789876543210
14. 
1
121
12321
1234321
15.
      *
    * *
   * * *
  * * * *
* * * * *
 * * * *
  * * *
    * *
      *
    

Comments

Popular posts from this blog

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS 1. Familiarization of Hardware Components of a Computer 2. Familiarization of Linux environment – Programming in C with Linux 3. Familiarization of console I/O and operators in C     i) Display “Hello World”     ii) Read two numbers, add them and display their sum     iii) Read the radius of a circle, calculate its area and display it 4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution. Read the values of the variables from the user through console 5. Read 3 integer values, find the largest among them. 6. Read a Natural Number and check whether the number is prime or not 7. Read a Natural Number and check whether the number is Armstrong or not 8. Read n integers, store them in an array and find their sum and average 9. Read n integers, store them in an array and search for an element in the    array using an algorithm for Linear Search 10.Read n integers, store them in an array and sort the elements in t

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper EST 102 Programmin in C University Question Papers  and evaluation scheme   EST 102 Programming in C  Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboar

Arrays in C-single and multi dimensional arrays- list and matrix

An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list(vector); A two dimensional array is like a table(matrix). We can have more dimensions. Always, Contiguous (adjacent) memory locations are used to store array elements in memory. Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element. Declaring  Single Dimensional Arrays Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for mentioning dimension of the array.  Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.  In C99, dimensions must still be positive integers, but variables can be used, so long as the variable has a positive value at the time the array is declared. ( Space is allo