I am new to C and I have this program where I am trying to print a triangle based on its height as such:
/\
/__\
So if the height is 2, then there are 2 of '/', '\' and '_'.
So I have written these chunk of codes:
#include <stdio.h>
int main(void)
{
int noOfRows;
printf("Enter height: ");
scanf("%d", &noOfRows);
int counter, rowNumber;
for (rowNumber = 0 ; rowNumber < noOfRows; rowNumber++)
{
// For each row, insert numberOfRows - N spaces before printing
for (counter = 0 ; counter < noOfRows- rowNumber ; counter++)
printf(" ");
// For each row, print N times the character
printf("/");
for (counter = 0; counter < noOfRows; counter++)
printf("\\");
printf(" ");
printf("\n");
}
return 0;
}
However it is giving me an output of such when I enter 3 as the height.
/\\\
/\\\
/\\\
I want to get the '\' with more space as each new row comes up but I am not sure how the for loop should be modified such that the triangle is formed correctly. Please let me know if I should add anymore question to make it clearer.
I made changes to the code and currently have this:
#include <stdio.h>
int main(void)
{
int noOfRows;
printf("Enter height: ");
scanf("%d", &noOfRows);
int counter, rowNumber;
for (rowNumber = 0 ; rowNumber < noOfRows; rowNumber++)
{
// For each row, insert numberOfRows - N spaces before printing
for (counter = 0 ; counter < noOfRows- rowNumber ; counter++)
printf(" ");
// For each row, print N times the character
printf("/");
for (counter = 0 ; counter < rowNumber ; counter++)
if(rowNumber >= 1)
for(int j=0; j<counter +1; j++)
printf(" ");
if(rowNumber != 0)
printf(" ");
printf("\\");
printf("\n");
}
return 0;
}
and now my current output is as such:
Height: 3
/\
/ \
/ \
Height: 5
/\
/ \
/ \
/ \
/ \
What did I do wrong in the code that is making some of the '\' go even further away?