'Remove trailing '+' sign in this output resulting from double for loops in C
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
Solution 1:[1]
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.
Solution 2:[2]
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");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jonathan Leffler |
| Solution 2 |
