# Tracing a asterisks triangle program

• 12-06-2012
C0__0D
Tracing a asterisks triangle program
Code:

```# include <stdio.h> void printTriangle(int num_rows)         {                 int currentRow;                 int currentStar;                 for(currentRow = 0; currentRow < num_rows; currentRow++)                 {                         for(currentStar = 0; currentStar <= currentRow + (currentRow / 3 ); currentStar++)                         {                                 printf("*");                         }                         printf("\n");                 }         } int main() {     printTriangle(5);     return 0; }```
On Line 9, Why must there be an integer division of current_row and 3? Can anyone elaborate on this concept please?
• 12-06-2012
Matticus
Learning to follow a program step by step is a vital skill when you're trying to master the concepts.

Let's look at the inner loop.

Code:

```/* loop 1 */ currentRow = 0 currentStar <= currentRow + (currentRow / 3 ) This is how many stars you want to print on the first loop. currentRow + (currentRow / 3 ) = 0 + 0/3 = 0 + 0 = 0 Because of the "<=", you will print one star. /* loop 2 */ currentRow = 1 currentStar <= currentRow + (currentRow / 3 ) currentRow + (currentRow / 3 ) = 1 + 1/3 = 1 + 0 = 1 Two stars will be printed. /* loop 3 */ currentRow = 2 currentStar <= currentRow + (currentRow / 3 ) currentRow + (currentRow / 3 ) = 2 + 2/3 = 2 + 0 = 2 Three stars will be printed. /* loop 4 */ currentRow = 3 currentStar <= currentRow + (currentRow / 3 ) currentRow + (currentRow / 3 ) = 3 + 3/3 = 3 + 1 = 4 Five stars will be printed. etc...```
Notice that this is not a perfectly stepped printout, as dictated by the logic.

Also remember that integer division truncates the result, which is why "currentRow/3" produces zero when "currentRow" is 0, 1, and 2.
• 12-06-2012
C0__0D
Matticus strikes again! Thank you!
• 12-06-2012
Matticus
You're very welcome! And I just correct an error in my post - for the last case, I accidentally had "Four stars will be printed."
• 12-06-2012
Salem
> On Line 9, Why must there be an integer division of current_row and 3? Can anyone elaborate on this concept please?
You could
change it to /2, run the code and observe the changes to the output.
change it to /4, run the code and observe the changes to the output.
• 12-06-2012