'How to stop printing comma and space after last digit in c
Here is the program I wrote:
int main(void)
{
int d1, d2;
d1 = 48;
while (d1 < 58)
{
d2 = d1 + 1;
while (d2 < 58)
{
putchar(d1);
putchar(d2);
putchar(',');
putchar(' ');
d2++;
}
d1++;
}
putchar(10);
return (0);
}
Output of the program is as follows:
01, 02, 03, 04, 05, 06, 07, 08, 09, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26, 27, 28, 29, 34, 35, 36, 37, 38, 39, 45, 46, 47, 48, 49, 56, 57, 58, 59, 67, 68, 69, 78, 79, 89, $
I want the output like this:
01, 02, 03, 04, 05, 06, 07, 08, 09, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26, 27, 28, 29, 34, 35, 36, 37, 38, 39, 45, 46, 47, 48, 49, 56, 57, 58, 59, 67, 68, 69, 78, 79, 89$
How can I get the comma to stop before last digit?
Solution 1:[1]
There are many ways to solve your problem. You can print a separator before each of the outputs except the first one.
Note also that it would be much more readable to use '0'
and '9'
instead of hard coding ASCII values such as 48
...
Here is a modified version:
#include <stdio.h>
int main() {
int d1, d2, n = 0;
for (d1 = '0'; d1 <= '9'; d1++) {
for (d2 = d1 + 1; d2 <= '9'; d2++, n++) {
if (n > 0) {
putchar(',');
putchar(' ');
}
putchar(d1);
putchar(d2);
}
}
putchar('\n');
return 0;
}
Here is an alternative using a separator string:
#include <stdio.h>
int main() {
int d1, d2;
const char *sep = "";
for (d1 = '0'; d1 <= '9'; d1++) {
for (d2 = d1 + 1; d2 <= '9'; d2++) {
fputs(sep, stdout);
sep = ", ";
putchar(d1);
putchar(d2);
}
}
putchar('\n');
return 0;
}
Solution 2:[2]
A different way of doing what @chqrlie does i.e. to print separator before each character.
Before the first character the separators are null characters and for subsequent characters the separators are ','
and ' '
.
Implementation:
int main(void)
{
int d1, d2;
int sep1 = 0;
int sep2 = 0;
d1 = 48;
while (d1 < 58)
{
d2 = d1 + 1;
while (d2 < 58)
{
putchar(sep1);
putchar(sep2);
putchar(d1);
putchar(d2);
d2++;
sep1 = ',';
sep2 = ' ';
}
d1++;
}
putchar(10);
return (0);
}
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 | |
Solution 2 | H.S. |