Thursday, 5 March 2015

Nesting of Loops

Like the conditional structures loops can also be nested inside one another. You can nest loops of any kind inside another to any depth you want. However having large number of nesting will reduce the readability of your source code.

Example 5.3 – Write a C program to display the following pattern:

$$$$$$$$$$
$$$$$$$$$$
$$$$$$$$$$
$$$$$$$$$$
$$$$$$$$$$

There are 10 “$” symbols in a single row (10 columns) and there are 5 rows. This can be implemented by having a two loops one nested inside another which print individual “$” symbols. However the printf function does not support displaying text on a row that you have already printed. Therefore first you need to fully complete the first row and then you should go to the next. Therefore the loop which handles printing of individual rows should be the outer loop and one which prints elements within a row (columns) should be the inner loop. Program-5.6 displays the above symbol pattern.

/* Program-5.6 */

#include <stdio.h>
int main()
{
int i,j;
for(i=0;i<=5;i++) //outer loop
{
for(j=0;j<=10;j++) // inner loop
{
printf("$");
} // end of inner loop
printf("\n");
} //end of outer loop
return 0;
}

Exercise 5.7 – Write a C program to display the following symbol pattern:

*
**
***
****
*****
******

No comments:

Post a Comment