C: Right Triangle (For-loop)

One of the basic lessons we had in looping, was creating figures, such as a triangle. In this post, I will be discussing how to create a program which will print a right triangle using looping statements in C.

For this program, three variables will be declared as integers, let us name them as, i, jand n. Variable i is the counter variable for the outer loop. Variable j is the counter variable for the inner loop, and variable n is the length of each side of the triangle.

   int i,j,n;  

Variable n will be provided by the user.

   printf("Enter number of rows for pyramid: ");   
   scanf("%d", &n);   

There will be two for-loops to be used here. The outer for-loop is responsible for each row printed. The inner for-loop is responsible for each asterisk (*) printed (from the 1st count to the nth count).

   for(i = 1; i <= n; i++)   
   {   
    for(j = 1; j <= i; j++)  
     printf("*");   
    printf("\n");   
   }   

Here is a sample input and output, with n is 5.


Here is the source code.

 #include <stdio.h>  
 int main()  
 {  
   int i,j, n;  
   printf("Enter number of rows for pyramid: ");  
   scanf("%d", &n);  
   printf("\n");  
   for(i = 1; i <= n; i++)   
   {  
     for(j = 1; j <= i; j++)  
       printf("*");  
     printf("\n");  
   }  
   printf("\n\n");   
   return 0;  
 }