Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

C: Printing A Triangle

Tags: loop
This program will demonstrate how a triangle can be printed using nested loops within the command line output of a console application.


Let us begin with the headers.
//WinterNurf Productions

#include<stdio.h>

#include<conio.h>

We now begin the main() function and declare two loop control variables.
int main()
{
      //Declare loop cotrol variables
      inti = 0;

      intj = 0;

To display the triangle, we will need to print a character on the screen. Any character can be used here. However, we have used the ASCII value of 221 in this example as it provides a nice visual touch.
      //Declare and initialize the character to be displayed

      charchDisplay = 221;

We will now create the outer loop of our nested loop. This will be used to iterate rows (as our triangle is essentially a matrix of pixels).
      //Create an outer loop to iterate rows
      for(i = 0; i <= 30; i += 2)

      {

Within the loop, we first print a newline character. This is used to complete printing one row and bring the cursor to the next row.
            //Print a newline character

            printf ("\n  ");

We will create two inner loops. The first one will be used to print spaces (because we want some space before printing our character).
            //Create an inner loop and print spaces
            for(j = 30; j >= i; j -= 2)

                  printf ("  ");

The second inner loop is used to print the actual triangle.
            //Create another loop to print the triangle
            for(j = 0; j <= i; j++)
                  printf ("%c ", chDisplay);

      }

Thats't it! We now end the program.
      _getch();
      return 0;

}

Here is the full code.
//WinterNurf Productions

#include<stdio.h>
#include<conio.h>

int main()
{
      //Declare loop cotrol variables
      inti = 0;
      intj = 0;

      //Declare and initialize the character to be displayed
      charchDisplay = 221;

      //Create an outer loop to iterate rows
      for(i = 0; i <= 30; i += 2)
      {
            //Print a newline character
            printf ("\n  ");

            //Create an inner loop and print spaces
            for(j = 30; j >= i; j -= 2)
                  printf ("  ");

            //Create another loop to print the triangle
            for(j = 0; j <= i; j++)
                  printf ("%c ", chDisplay);
      }

      _getch();
      return 0;

}

This program has been written in Microsoft Visual Studio for Desktop. It may not work in older compilers. However, simple editing will make the code compatible.


This post first appeared on Code Walk, please read the originial post: here

Share the post

C: Printing A Triangle

×

Subscribe to Code Walk

Get updates delivered right to your inbox!

Thank you for your subscription

×