Search code examples
cnested-for-loop

Can anyone help me understand how this code prints a triangle?


I don't understand how this code displays a triangle. My main problem is understanding the working of integers j and k. How do they affect the triangle's position?

#include <stdio.h>

int main(){
    int j,k,Rows;
    printf("Enter The Number of Rows : ");
    scanf("%d", &Rows);

    for(j=2;j<=l;j++){
        for(k=1;k<=j;k++){
            printf("  %d ", j);
        }
        printf("\n");
    }
    return 0;
}

Solution

  • I guess the program you want is

    #include <stdio.h>
    
    int main(){
        int j,k,Rows;
        printf("Enter The Number of Rows : ");
        scanf("%d", &Rows);
    
        for(j=1;j<=Rows;j++){
            for(k=1;k<=j;k++){
                printf("  %d ", j);
            }
            printf("\n");
        }
        return 0;
    }
    

    Changes are:

    • Change l to Rows
    • Change j=2 to j=1

    And here is an example result

    Enter The Number of Rows : 6
      1 
      2   2 
      3   3   3 
      4   4   4   4 
      5   5   5   5   5 
      6   6   6   6   6   6
    

    My main problem is understanding the working of integers j and k. How do they affect the triangle's position?

    j here can represent the row index. k can represent the column index. In another word, k represents how many items in current row. for(k=1;k<=j;k++) means the max value of k is j. Since j is increased by 1, so the max value of k is also increased by 1:

    口          # j = 1, the max value of k is 1, so this row has 1 item.
    口 口       # j = 2, the max value of k is 2, so this row has 2 items.
    口 口 口    # j = 3, the max value of k is 3, so this row has 3 items.
    口 口 口 口 # j = 4, the max value of k is 4, so this row has 4 items.