UncleCoder.com

UncleCoder.com

Free programming examples and instructions

C program to generate a pattern

C program to print a pattern by numbers. The input will be a number and based on that number the pattern will be generated.

by Krishna viswambharan


Posted on 16 Aug 2017 Category: C Views: 114

Edited on 16 Aug 2017



C program to generate the following pattern

                 

              0

              0 1

              0 1 2

              …………

              ………………n

C programming allows to use one loop inside another loop. In the last sections we have learned how to use the ‘for loop’ in C language

Here we go for ‘nested for loop’ and its sample implementation

The syntax for a nested for loop statement in C is as follows:-

for ( init; condition; increment ) {

   for ( init; condition; increment ) {
      statement(s);
   }
	
   statement(s);
}

Firstly the ‘condition’ of the first ‘for loop’ is checked and if it is true , it goes to the next ‘for loop’ condition and execute the statements and it increment the second ‘for loop’ and again check the condition , if it goes false it return to the first ‘for loop’ and increment the  first ‘for loop’.  This process repeats until the first for loop condition get false.

Here is a sample program to generate the above pattern

#include <stdio.h>
#include <conio.h>
void main()
{
	int i,j,n;
	printf("Enter the limit to generate the pattern :”);
	scanf(“%d’,&n);
	for(i=0;i<=n;i++)
	{
		for(j=0;j<=i;j++)
		{
			printf(“%d”, j);
			printf(“\t”);  // to give tab space 
		}
		printf(“\n”);  // newline
	}
	getch();
}	 

 Here it first check the upper for loop condition that is (i<=limit given) if it is true, it checks the nested loop condition that is (j<=i) and if true print the j value. Then it increment the ‘j’ value count and checks the lower loop condition if it get false it moves to the upper loop and increment the ‘i’ value count and check the condition . this process repeats until the upper loop condition become false.



Leave a Comment:


Advertisement