Majd
Majd

Reputation: 348

Formatted output in C based on end condition

I am Iterating over some counters in C to print the results on a single line separated like this 012, 013, 014, etc...

My code comes to an end based on some conditions and it's being corrected by a bot.

how can i stop printing the , after the last value of my code. the idea s to get a 3 digit number with only unique digits and in ascending order ending with 789;

My function goes as follows:

void my_print_comb(void){
   for(int i = 47; i++ < 57 ; ){
      for(int j = 48; j++ < 57 ; ){
         for(int k = 49; k++ < 57 ; ){
             if( i != j && i != k && j != k){
                while( i < j && j < k){
                char a = i, b = j, c = k;
                my_putchar(a);
                my_putchar(b);
                my_putchar(c);
                my_putchar(',');
                my_putchar(' ');
                break;
                }
             }
         }
      }
   }
}

Upvotes: 2

Views: 107

Answers (1)

icebp
icebp

Reputation: 1709

Print one of the elements without the comma. Either print the first one and then iterate through the rest of the array and print each element with a , in front of it; or print all the elements except the last one with a , after each one, then print the last one. I like the first approach more.

Since you did not show any code I'm just going to give an example.

void pretty_print_ints(const int *array, size_t count)
{
    // Nothing to do.
    if (count == 0 || array == NULL) return;

    // Print the first element, without a `,` after it.
    printf("%d", array[0]);

    // If there are more elements in the list, print them all, but add a `, ` separator.
    for (size_t i = 1; i < count; i++) printf(", %d", array[i]);

    // Add a new line at the end.
    printf("\n");
}

It also works if we don't know how many elements we have to print. For example, instead of stopping when we printed count elements we could stop when we hit an element equal to 0, the only thing we need to change is the stop condition. If we went the other way around (print count - 1 elements with printf("%d, ", array[i]); we won't be able to handle this case).

Upvotes: 5

Related Questions