Printing triangle in C

3k Views Asked by At

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?

4

There are 4 best solutions below

1
vishalkuma2 On BEST ANSWER

You can use only two loop to print this pattern by using if else. in if else you can use multiple condition for space, backslash,forward-slash and underscore.

1 #include<stdio.h>
  2 
  3 int main()
  4 {
  5         int n;
  6         int i,j,k;
  7         printf("Enter hight of trangle\n");
  8         scanf("%d",&n);
  9         for(i=0;i<n;i++,printf("\n"))
 10         {
 11                 for(j=-n;j<=n;j++)
 12                 {
 13                         if(j<0) k=-j;
 14                         else    k=j;
 15 
 16                         if(j==0);
 17                         else if((j<0)&&(k==(i+1)))
 18                                 printf("/");
 19                         else if((j>0)&&(k==(i+1)))
 20                                 printf("\\");
 21                         else if((i+1)==n)
 22                                 printf("_");
 23                         else
 24                                 printf(" ");
 25                 }
 26         }
 27 }
1
Barmar On

You don't need two nested loops to print the spaces between / and \\. It should just print rowNumber*2 spaces.

for (counter = 0; counter < rowNumber*2; counter++) {
    printf(" ");
}

You don't need to test if (rowNumber >= 1), because when it's 0 the loop ends immediately.

However, you do need a check for the last row, because you're supposed to print _ instead of space. So it should be:

for (counter = 0; counter < rowNumber*2; counter++) {
    if (rowNumber == noOfRows-1) {
        printf("_");
    } else {
        printf(" ");
    }
}
0
YlmzCmlttn_Old On

@Barmar's idea is true and anymore you don't need if(rowNumber != 0) printf(" ");

Fullcode:

#include <stdio.h>
int main(void)
{
    int noOfRows; 
    printf("Enter height: ");
    scanf("%d", &noOfRows);
    int counter, rowNumber;
    for (rowNumber = 0 ; rowNumber < noOfRows; rowNumber++)    {

        for (counter = 0 ; counter < noOfRows- rowNumber ; counter++)
            printf(" ");        
            printf("/");
        for (counter = 0 ; counter < rowNumber ; counter++)
            if(rowNumber >= 1)  
                for (counter = 0; counter < rowNumber*2; counter++) {
        if (rowNumber == noOfRows-1) {
        printf("_");
        } else {
        printf(" ");
        }
        }
        printf("\\");
        printf("\n");
    }

}
0
assefamaru On

Alternatively, you can abstract the repetitive printing of chars as:

// print_char(n,c) prints c n-times.
void print_char(int n, char c) {
  for (int i = 0; i < n; ++i) {
    printf("%c", c);
  }
}

so that you only have to keep track of one for loop when constructing the triangle as:

void print_triangle(int height) {
  for (int i = 1; i <= height; ++i) {
    print_char(height-i, ' ');               // print leading empty spaces
    printf("/");                             // print forward slash
    if (i == height) {                       // print middle dashes/spaces
      print_char((height-1)*2, '_');         //             <--|      |
    } else {                                 //                       |
      print_char((i-1)*2, ' ');              //             <---------|
    }
    printf("\\\n");                          // print backslash
  }
}

For example,

int main(void) {
  int height;
  printf("Enter height: ");
  if (scanf("%d", &height) != 1) {
    // handle error if scanf fails
  }
  print_triangle(height);
  return 0;
}

and then,

$ Enter height: 1
/\
$ Enter height: 5
    /\
   /  \
  /    \
 /      \
/________\