C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Let's observe an example of nesting loops in C. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
Syntax:
for( initial ; Condition ; increment / decrement ) // Outer Loop Statements
{
for( initial ; Condition ; increment / decrement ) // Inner Loop Statements
{
. . . .
}
}
This program is written in C language and uses nested for loops to print two different patterns of asterisks (*).
The first for loop, with the loop variable "i" starts at 0 and runs for 5 iterations. Within this for loop, there is another for loop, with the loop variable "j", which also starts at 0 and runs for 5 iterations. The inner for loop prints an asterisk (*) on each iteration, so it will print 5 asterisks in total during each iteration of the outer for loop. This creates a pattern of 5 rows of 5 asterisks each.
Then a line of separator is added to distinguish the two different patterns
The second set of nested loops starts with i = 1 and runs for 5 iterations. Within this for loop, there is another for loop, with the loop variable "j" which starts at 1 and runs for i iterations. The inner for loop prints an asterisk (*) on each iteration, so it will print i asterisks in total during each iteration of the outer for loop. This creates a pattern of 5 rows of asterisks, with the first row having 1 asterisk, the second row having 2 asterisks, and so on, up to the fifth row which has 5 asterisks.
In the end, the main function returns 0 to indicate successful execution of the program.
//Nested For Loop /* ***** ***** ***** ***** ***** * ** *** **** ***** */ #include<stdio.h> int main() { int i,j; for(i=0;i<5;i++) { for(j=0;j<5;j++) { printf("*"); } printf("\n"); } printf("\n----------------------------\n"); for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf("*"); } printf("\n"); } return 0; }To download raw file Click Here
* * * * * * * * * * * * * * * * * * * * * * * * * ---------------------------- * * * * * * * * * * * * * * *
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions