Nesting of loops in C

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");
     
}

Write a C program to check whether the given number is Armstrong number or not. [Hint: An Armstrong number is a number with the sum of digits raised to the power of number of digits, returns the number. ( university question)
Example: 153 = 1^3 + 5^3+ 3^3=1+125+27=153
9474=9^4 + 4^4 + 7^4 + 4^4 = 6561 + 256 + 2401 + 256=9474
#include <stdio.h>
#include <math.h>

int main() {
    int num, original, remainder, n = 0;
    double result = 0.0;

    printf("Enter a number: ");
    scanf("%d", &num);

    original = num;

    // Count number of digits
    int temp = num;
    while (temp != 0) {
        temp /= 10;
        n++;
    }

    // Compute sum of digits raised to the power n
    temp = num;
    while (temp != 0) {
        remainder = temp % 10;
        result += pow(remainder, n);
        temp /= 10;
    }

    // Check if it's an Armstrong number
    if ((int)result == original)
        printf("%d is an Armstrong number.\n", original);
    else
        printf("%d is not an Armstrong number.\n", original);

    return 0;
}

Write a C program to display the first 50 prime numbers ( University Question)

#include <stdio.h>

int main() {
    int count = 0;   // Number of primes found
    int num = 2;     // Number to check for primality

    printf("First 50 prime numbers:\n");

    while (count < 50) {
        int isPrime = 1;  // Assume num is prime

        // Check if num is divisible by any number from 2 to sqrt(num)
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                isPrime = 0;  // num is not prime
                break;
            }
        }

        if (isPrime) {
            printf("%d ", num);
            count++;
        }

        num++;
    }

    printf("\n");
    return 0;
}


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; 
}

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

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

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays