Home > Software engineering >  How to remove the comma in the last number?
How to remove the comma in the last number?

Time:12-31

The list must show this "1,2,3,4" but in this code it shows like this "1,,2,,,3,,,4" What could be wrong in this code?

for (i = 1; i <= num1;   i) {
    if(num1 % i == 0)
        printf("%d",i);
    if(i<num1)
        printf(",");
}

CodePudding user response:

Comma has to be printed only when you are printing a number, so put it in the same if.

for(i = 1; i <= num1;   i) {
      if(num1 % i == 0){
          printf("%d",i);
          if(i<num1)
            printf(",");
      }
}

CodePudding user response:

The problem is that you are printing , even for numbers that don't pass the check

Fixed:

for (i = 1; i <= num1;   i) {
    if (num1 % i == 0) {
        printf("%d", i);
        if (i < num1)
            printf(",");
    }
}

printf("\n");

The above relies on the last element passing the check. Because that's the case, it can be simplified to the following:

for (i = 1; i < num1;   i) {
    if (num1 % i == 0) {
       printf("%d,", i);
    }
}

printf("%d\n", num1);

But, generally speaking, you can't rely on the last number passing the check. The following is a more general approach that doesn't rely on the last number passing the check:

const char *prefix = "";
for (i = 1; i <= num1;   i) {
    if (num1 % i == 0) {
       printf("%s%d", prefix, i);
       prefix = ",";
    }
}

printf("\n");

CodePudding user response:

Or more efficiently than above:

for (i = 1; i < num1;   i) {
    if (num1 % i == 0) {
        printf("%d,",i);
    }
}
printf("%d",num1);

In other words:

  1. No need to check i < num1 at every iteration
  2. No need to check num1 % i == 0 at the last iteration

CodePudding user response:

To avoid if or the conditional operator (?:) I usually just print the first item outside the loop

printf("1");                       // 1
for (i = 2; i <= num1;   i) {                             // note: start at 2
    if (num1 % i == 0) {
        printf(", %d", i);         // , 2, 3, 4, ..., n
    }
}
printf("\n");                      // newline

CodePudding user response:

Here's the really short version, using the ternary operator:

#include <stdio.h>

int main(void) {
    int num1=24;
    
    for (int i = 1; i <= num1;   i)
        printf((num1%i)? "": "%d%s", i, (i<num1)? "," : "");
    
    return 0;
}

Output:

Success #stdin #stdout 0s 5660KB
1,2,3,4,6,8,12,24
  • Related