C Programming

Solved Example

Practice Questions

Exercise Question

C program to print triangle pattern

Objective

Write a program to input the number of rows and print the triangle pattern for n rows as shown below...

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

Program

#include"stdio.h"
int main() {
	int n, i, j, k;
	printf("Enter the rows to print: ");
	scanf("%d",&n);
	
	//Rotate loop for n rows
	for(i = 1; i <= n; i++) {
		
		//loop for spaces
		for(j = 1; j <= n - i; j++) {
			printf("%c",32);
		}
		//loop for printing *
		for(k = 1; k <= 2 * i - 1; k++) {
			printf("*");
		}
		
		
		//switch to new line in each row
		printf("\n");
	}
	return 0;
}

Output

Enter the rows to print: 10
         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************