Simple Looping in C: Creating a Star Pattern

Introduction

In this example, we'll explore how to use loops in C to create a simple pattern of stars, resembling a staircase. Instead of manually writing out each line of stars, we can efficiently achieve this using loops.

Manual Star Pattern

Let's first manually create a staircase pattern with four rows:

*
* *
* * *
* * * *

We can achieve this by writing out the code like this:

#include <stdio.h>

int main() {
    printf("*\n");
    printf("* *\n");
    printf("* * *\n");
    printf("* * * *\n");

    return 0;
}

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

Using Loops for Efficiency

Now, imagine needing to create a staircase with a larger number of rows, say 100 or 1000. Manually writing each line would be impractical. This is where loops come in handy.

Let's use a loop to create a pattern with 5 rows as an example:

#include <stdio.h>

int main() {
    int firstLoop;
    for (firstLoop = 1; firstLoop <= 5; firstLoop++) {
        printf("%d ", firstLoop);
        for (int secondLoop = 1; secondLoop <= firstLoop; secondLoop++) {
            printf("* ");
        }
        printf("\n");
    }
    printf("\n");
    for (firstLoop = 1; firstLoop <= 5; firstLoop++) {
        printf("%d ", firstLoop);
        for (int secondLoop = 1; secondLoop <= firstLoop; secondLoop++) {
            printf("%d ", secondLoop);
        }
        printf("\n");
    }

    return 0;
}

This code consists of two loops. The outer loop controls the number of rows, and the inner loop prints the corresponding number of stars for each row.

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

By adjusting the loop limits, you can easily create staircase patterns of varying sizes without the need for manual repetition. This demonstrates the power of using loops to simplify and optimize repetitive tasks in programming.