6

I'm trying to print the elements of an array separated by commas.

My output:

5,6,7,8,9, 

I need to get rid of the last comma, anyone know how to do that?

#include <stdio.h>
#include <stdlib.h>

void print_array(int integers[], int  elements);

int main(){
    
    int arr[5] = {5, 6, 7, 8, 9};
    print_array(arr, 5);
    
    return 0;
    
}

void print_array(int integers[], int elements){
    
    int j; 
    for(j=0; j<elements; j++){
        printf("%d,", integers[j]);
        
    }
}
einpoklum
  • 118,144
  • 57
  • 340
  • 684
Bob Jones
  • 61
  • 2
  • Remove the comma from your format specifier string, and execute `if (j < elements - 1) printf(", ");` right below your first `printf` statement. – Robert Harvey Mar 12 '22 at 22:32
  • Or skip the first one instead with `if(j) { printf(","); } printf("%d", integers[j]);` – Weather Vane Mar 12 '22 at 22:38
  • 1
    The least space, `printf("%s%d", j ? ", " : "", integers[j]);`, is arguably best for readability and code re-use. The i/o costs probably dwarf whatever performance gain one gets by unrolling. – Neil Mar 12 '22 at 23:25

4 Answers4

4

This is actually a frequent pattern in programming: You have a sequence of elements, and you want to do something both for every element and for every pair of consecutive element, i.e. for every gap between consecutive elements.

Anyway, here are a few options:

  1. Iterate all elements except the last one (knowing they all have a subsequent element), treat the last one separately
  2. Treat the first element separately, then iterate all elements after the first one (knowing they all have a previous element).
  3. Iterate all elements, but check for whether you're at the final element
  4. Iterate all elements, use a boolean to remember when you're already past the first element (i.e. you set the boolean when you find it to be false).
  5. Iterate all elements, acting as though they all had a subsequent element, then perform a corrective action to undo the work on the non-existing pair of subsequent elements at the end.

Here's an example for your case of the first option:

void print_array(int integers[], size_t num_elements)
{
    if (num_elements == 0) { return; }
    for(size_t j = 0; j < num_elements - 1; j++){
        printf("%d,", integers[j]);
    }
    printf("%d", integers[num_elements - 1]);
}

Notes:

  • It is tricky to avoid code duplication altogether with this pattern.
  • elements is a confusing name (it makes you think that variable has the actual elements), I replaced it with num_elements.
  • A similar question about C++: How can I print a list of elements separated by commas?
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 4
    Nobody every recommends the fun way, `for (int j = 0; j < elements; ++j) printf("%3d ", integers[j]); for (int j = 0; j < elements-1; ++j) printf("\b\b\b\b\b,"); printf("\n");`. – Eric Postpischil Mar 12 '22 at 23:13
3

Recommend to change the separator after printing.

void print_array(const int integers[], int elements) {
  const char *separator = ""; 
  for(int j=0; j<elements; j++) {
    printf("%s%d", separator, integers[j]);
    separator = ",";
  }
  printf("\n");
}

Notice this works well even if elements == 0 and does not need any special if() blocks or ?: statements.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

Elaborating on einpoklum's answer, this is how I would do it (option 3):

#include <stdio.h>
#include <stdbool.h>

void print_array(int integers[], size_t num_elements) {
    for(size_t j = 0; j < num_elements; j++) {
        bool is_last_element = (j + 1) == num_elements;
        printf("%d", integers[j]);

        if (!is_last_element) {
            printf(",");
        }
    }
}

int main(void) {
    int ints[4] = {1,2,3,4};

    print_array(ints, 4);
}

This has the advantage of:

  • We don't have to check for zero elements.
  • The counter variable j stays local to the for-loop (this is arguably minor but still a plus)
  • No code duplication
Marco
  • 7,007
  • 2
  • 19
  • 49
0

What I usually do is print the first element special avoiding a if inside the loop

void print_array(const int *integers, size_t elements, const char *pref, const char *postf) {
    if (pref) printf("%s", pref);
    printf("%d", integers[0]);              // 1st element
    for (size_t j = 1; j < elements; j++) {
        printf(", %d", integers[j]);        // 2nd, 3rd, ... elements
    }
    if (postf) printf("%s", postf);
}

int main(void) {
    int arr[5] = {5, 6, 7, 8, 9};
    print_array(arr, 5, 0, 0);
    print_array(arr, 5, "arr is {", "}\n");
    return 0;
}
pmg
  • 106,608
  • 13
  • 126
  • 198