Problem Solving using C Language

0 of 57 lessons complete (0%)

Loops

Lab: for Loop Patterns

You don’t have access to this lesson

Please complete the prerequisites to view this lesson content.

Pattern 1: Print Right-Angle Triangle
For N = 5:

*
* *
* * *
* * * *
* * * * *
#include <stdio.h>

int main() {
    int N;

    printf("Enter a number: ");
    scanf("%d", &N);

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

    return 0;
}

Pattern 2: Print Inverted Right-Angle Triangle

For N = 5:

* * * * *
* * * *
* * *
* *
*
#include <stdio.h>

int main() {
    int N;

    printf("Enter a number: ");
    scanf("%d", &N);

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

    return 0;
}