We begin with the headers.
//WinterNurf Productions
#include<stdio.h>
#include<conio.h>
We will now begin the main() function and declare two loop control variables because we will be creating two nested loops.
int main()
{
//Declare loop cotrol variables
inti = 0;
intj = 0;
To display the triangle, we will need a character. In this example we are using the ASCII value of 221. Feel free to use any character in its place.
//Declare and initialize the character to be displayed
charchDisplay = 221;
We will now create the outer loop and use it to iterare through rows. Immediately within the loop, we will first print a newline character. This will be printed when one row has ended, and can also be put at the end of the loop.
//Create an outer loop to iterate rows
for(i = 0; i <= 30; i += 2)
{
//Print a newline character
printf ("\n ");
We need to print some spaces to the left of our triangle, and we will do that using a loop within our outer loop.
//Create an inner loop and print spaces
for(j = 30; j >= i; j -= 2)
printf (" ");
We will now create another loop to print the actual triangle. Since we want the triangle to be hollow, we will print the character only when the position is at the boundary of the triangle, i.e. in the first row, first column (of each row), last row and last column (of each row). For the rest of the positions, we will print spaces to fill in the triangle.
//Create another loop to print the triangle
for(j = 0; j <= i; j++)
//Print the character only if on boundary
if(i == 0 || i == 30 || j == 0 || j == i)
printf ("%c ", chDisplay);
//Else, print a space to fill the space in between
else
printf (" ");
}
That is all we need to print a hollow triangle. 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++)
//Print the character only if on boundary
if(i == 0 || i == 30 || j == 0 || j == i)
printf ("%c ", chDisplay);
//Else, print a space to fill the space in between
else
printf (" ");
}
_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.