How to Print a Triangle in C
A common programming problem given to students in an introductory C programming class is how to print a triangle. This program requires knowledge of control structures, like the "for loop." A for loop executes a block of code a number of times. You can place a for loop inside the code block of another for loop, creating a nested for loop. This is the key to solving this problem. By nesting two for loops, you can print a triangle.
Things You'll Need
- C Integrated Development Environment (IDE), such as Eclipse CDT
- C Compiler, such a GCC
Instructions
-
-
1
Load the C IDE by clicking on its program icon. When it opens, select "File/New/Project" and choose "C Project" to create a new C project. A blank source code file appears in the text editor portion of the IDE.
-
2
Import the following two libraries by typing in the following statements at the top of the source code file:
#include <stdio.h>
#include <stdlib.h>
-
-
3
Create a main function. The main function is the starting point for your program. You will place all of your code inside the main function. Type the following below the "include" statements to declare a main function:
int main()
{}
-
4
Create an outer for loop. The purpose of this for loop is to create a series of rows. Write the following between the brackets of the main function to create a for loop that makes 10 rows:
for(int i = 0; i < 9; i++)
{}
-
5
Create a nested for loop. The nested for loop creates a series of columns in a triangular pattern by limiting the amount of columns made, based on the current row. For example, on row one, one column is made. On row two, two columns are made. To create the nested for loop that is limited in this manner, write the following between the curly brackets of the first for loop:
for(int j = 0; j < i; j++)
{ printf("X"); }
-
6
Create a new line that separates each row. Write the following statement below the nested for loop, but between the curly brackets of the first for loop:
printf("\n");
-
7
Execute the program by pressing the green play button. The program output looks like this:
X
XX
XXX
XXXX
XXXXX
XXXXXX
XXXXXXX
XXXXXXXX
-
1