Remove trailing '+' sign in this output resulting from double for loops in C

Viewed 53

In the code attached, how do I modify it to remove Remove the trailing '+' signs.

int i,j,sum;
sum=1;

for(i=2; i<=10; i++) {
    for(j=1; j<(i+1); j++) {
        sum = sum + 1;
        printf("%d + ",j);
    }
    printf(" = %d", sum);
    printf("\n");
}

return EXIT_SUCCESS;

}

Here is the output:

1 + 2 +  = 3
1 + 2 + 3 +  = 6
1 + 2 + 3 + 4 +  = 10
1 + 2 + 3 + 4 + 5 +  = 15
1 + 2 + 3 + 4 + 5 + 6 +  = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 +  = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 +  = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +  = 45
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 +  = 55
  
3 Answers

For example you can do it the following way

for(j=1; j<(i+1); j++) {
    sum = sum + 1;
    if ( j != 1 ) printf( " + " );
    printf("%d",j);
}

You can't 'remove' output; you have to avoid generating it.

One way is to use:

for (int i = 2; i <= 10; i++)
{
    int sum = 0;
    const char *pad = "";
    for (int j = 1; j <= i; j++)
    {
        sum += j;
        printf("%s%d", pad, j);
        pad = " + ";
    }
    printf(" = %d\n", sum);
}

Note that this recalculates sum more directly, setting it to zero before the inner loop. It also minimizes the scope of the variables.

You can set and print the initial value in the outer loop. For my opinion also make it more readable. Furthermore you can use j instead of sum+1 for the addend

for (int i = 2; i <= 10; i++) {
    int sum = 1;
    printf("%d", sum);
    for (int j = 2; j<(i + 1); j++) {
        sum += j;
        printf(" + %d", j);
    }
    printf(" = %d", sum);
    printf("\n");
}
Related