Right-angled triangle pattern

·

2 min read

You can create useful patterns in c to learn more about loops . To print the pattern we will have to make use of a nested loop. In this tutorial, i will be using for loop to demonstrate how to print patterns. Without much further ado we will look at printing our first pattern which is a right-angled triangle using a star. Open a text editor for this tutorial I will be using vim editor. Create a c source file named rightAngledStar.c and open and write the following piece of code. Vim comes by default with the Unix Operating system. If you don't have vim text editor click here to download it.

/*right angled star pattern */
#include <stdio.h>
int main(void) /*entry point of program*/
{
    int i, j;
    for (i = 1; i <= 5; i++) /*loop starts at 1 upto 5 */
    {
        for(j = 1; j < = i; j++)/*runs all its iterations for each iteration of outer loop*/ 
        {
            printf("*");/* print star pattern */
        }
        printf("\n");/*go to next line*/
    }
    return 0;
}

After you have written the above code save your code by pressing ctrl+x. Use GNU Compiler Collection compiler to run it. It is a best practice to include additional flags with running gcc command. To enforce the strictness and make your code robust. I will cover that in a brief.

gcc -Wall -pedantic -Werror -wExtra -std=gnu89 rightAngledStar.c -o star

Explanation;

line 1: Multicomment style .The compiler usually ignores this piece of code.It explain the purpose of code.

line 2: header file which has the implementation of printf function.Used for printing output to screen.

line 4: declaration of variables to hold values.

int i, j;
for (i=1;i<=5;i++)
{
    for (j=1;j<=i;j++)
    {
        printf("*");
    /* inner loop starts from 1 upto the count number of times 
the outer loop will run which is i.
It prints output then inner count variable j increments 
until it finishes all iterations then execution goes back again
to the outer loop for the next iteration of outer loop*/
    }
    printf("\n");
}

To put it simply the code is like a clock that increases from digit 1 upto digit 12.

Additional flags in a brief;

-Wall: directs the compiler to give warning messages such as unused variables.

-pedantic: tells the compiler to strictly follow the language standard defined in gcc compiler by default.

-Werror: tells the compiler to treat all warnings as errors.

-wExtra: makes the compiler give you even more warning than the usual ones you signed up for.

-std=89: Tells the compiler to focus on adhering to gnu89 language rules.

Thanks for reading. See you in the next tutorial.