Home > Enterprise >  How to remove last whitespace after each line in c?
How to remove last whitespace after each line in c?

Time:05-01

I have to print out Pascal's triangle and my output is as follows-

1
1 1
1 2 1

My code gives the correct output but prints an extra whitespace after each line. Could someone please tell me how I can get rid of that. Here is my code-

//pascal

#include <stdio.h>

void pascal(int rows)
{
    int num = 1, i, j;

    for (i = 0; i < rows; i  )
    {
        for (j = 0; j <= i; j  )
        {
            if (j == 0 || i == 0)
            {
                num = 1;
            }
            else
            {
                num = num * (i - j   1) / j;
            }
            printf("%d ", num);
        }
        printf("\n");
    }
}

int main()
{
    int rows;
    printf("Please enter how many levels of Pascal's Triangle you would like to see: ");

    scanf("%d", &rows);

    pascal(rows);

    return 0;
}

CodePudding user response:

One way could be to print the space before the number and only print it if j > 0:

#include <stdio.h>
void pascal(int rows) {
    int num = 1, i, j;

    for (i = 0; i < rows; i  ) {
        for (j = 0; j <= i; j  ) {            
            if (j == 0 || i == 0) {
                num = 1;
            } else {
                num = num * (i - j   1) / j;
            }
            if (j > 0) putchar(' '); // conditionally print the space
            printf("%d", num);       // no space here
        }
        printf("\n");
    }
}

or print the first 1 before the loop:

void pascal(int rows) {
    int num = 1, i, j;

    for (i = 0; i < rows; i  ) {
        putchar('1');                  // print the first 1 here
        for (j = 1; j <= i; j  ) {     // and start the loop at 1
            if (i == 0) {              // only i needs to be checked here
                num = 1;
            } else {
                num = num * (i - j   1) / j;
            }
            printf(" %d", num);        // space before the number
        }
        printf("\n");
    }
}

CodePudding user response:

Fixing Your Whitespace Problem

To fix your whitespace problem, you simply need to conditionally output a space before the numbers you output for all values of j > 0. You can do that with a simple ternary operator changing only one line in your code, e.g.

            printf (j ? " %d" : "%d", num);

A bit more cleanup (and spacing for readability -- especially for older eyes) and your function becomes:

void pascal (int rows)
{
    int num = 1, i, j;

    for (i = 0; i < rows; i  )
    {
        for (j = 0; j <= i; j  )
        {
            if (j==0 || i==0)
            {
                num = 1;
            }
            else
            {
                num = num * (i - j   1) / j;
            }
            printf (j ? " %d" : "%d", num);
        }
        putchar ('\n');
    }
}

You also need to check the return of scanf() to ensure a valid integer value has been entered. (such as the user slipping and tapping 'r' reaching for '5'). You also need to validate the integer enter is greater than 0 (0 or negative values for rows makes no sense. You can do that with, e.g.

int main()
{
    int rows;
    
    fputs ("Enter No. of levels of Pascal's Triangle: ", stdout);

    if (scanf ("%d", &rows) != 1 || rows < 1) {
        fputs ("error: invalid integer input, or less than 1.\n", stderr);
        return 1;
    }

    pascal (rows);
}

(note: short and concise prompts are better than long-flowery prompts. printf() is only needed when a conversion is involved)

Example Use/Output

Now your triangle has no trialing whitespace, e.g.

$ ./bin/pascal_extra_ws
Enter No. of levels of Pascal's Triangle: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Printing A Balanced Triangle With Leading Whitespace

Another option in C is to use a VLA (Variable Length Array) to construct the triangle with a bit of creative indexing to define the triangle coefficients. You can do:

void pascal (int n)
{
    int array[n];                       /* declare VLA */
    memset (array, 0, sizeof array);    /* zero elements */

    printf ("\n  PASCAL's TRIANGLE\n(binomial coefficients)\n\n"
            "  exponent: %d\n\n", n);

    for (int i = array[0] = 1; i <= n;   i) {
        int j;
        printf ("%*s", (n - i)*3, "");
        for (j = i - 1; j > 0; --j)
            printf ("%-6d", array[j]  = array[j - 1]);
        printf ("%-3d\n", array[j]);
    }
}

(Note: there is no additional whitespace printed on the right side. To remove the leading whitespace and set the spacing between coefficients, you simply need to remove the printf() that outputs the leading spaces and adjust the field-width modifiers to your needs)

Which also has the benefit of printing a balanced triangle. A short working example taking the number of levels to print as the first argument to the program (or using 5 by default if no argument is given) can be written as:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

void pascal (int n)
{
    int array[n];                       /* declare VLA */
    memset (array, 0, sizeof array);    /* zero elements */

    printf ("\n  PASCAL's TRIANGLE\n(binomial coefficients)\n\n"
            "  exponent: %d\n\n", n);

    for (int i = array[0] = 1; i <= n;   i) {
        int j;
        printf ("%*s", (n - i)*3, "");
        for (j = i - 1; j > 0; --j)
            printf ("%-6d", array[j]  = array[j - 1]);
        printf ("%-3d\n", array[j]);
    }
}

int main (int argc, char **argv)
{
    char *endptr;
    /* take n as 1st argument to program (default 5) */
    int n = (argc > 1) ? strtol (argv[1], &endptr, 0) : 5;
    if (endptr == argv[1] || errno) {   /* vaidate conversion */
        fputs ("error: in argument conversion.\n", stderr);
        return 1;
    }
    
    pascal (n);
}

Example Use/Output

The first 12 levels of the triangle would be:

$ ./bin/pascal-triangle 12

  PASCAL's TRIANGLE
(binomial coefficients)

  exponent: 12

                                 1
                              1     1
                           1     2     1
                        1     3     3     1
                     1     4     6     4     1
                  1     5     10    10    5     1
               1     6     15    20    15    6     1
            1     7     21    35    35    21    7     1
         1     8     28    56    70    56    28    8     1
      1     9     36    84    126   126   84    36    9     1
   1     10    45    120   210   252   210   120   45    10    1
1     11    55    165   330   462   462   330   165   55    11    1
  •  Tags:  
  • c
  • Related