Wizard
Wizard

Reputation: 22113

Print a formatted array with "," and "{}"

I tried to print a formatted int array

#include <stdio.h>
#define SIZE 3
int arr[SIZE] = {1, 2, 3};

int main(void)
{   
    printf("{");
    for (int i =0; i < SIZE; i++ )
    {   
        printf("%d, ", arr[i]);
    }
    printf("}");
    printf("\n");

}

but found it very hard

$ ./a.out
{1, 2, 3, }

Extra comma is appended.

Is it possible to accomplish such a task in a facile way?

Upvotes: 1

Views: 212

Answers (5)

Bathsheba
Bathsheba

Reputation: 234795

Given that zero length arrays are not permitted in C (so arr[0] always exists), and you already have explicit code for the opening brace, this solution seems reasonable to me:

int main(void)
{   
    printf("{%d", arr[0]);
    for (size_t/*better type for array index*/ i = 1; i < SIZE; ++i)
    {   
        printf(", %d", arr[i]);
    }
    printf("}\n");
}

Reference: What is the correct type for array indexes in C?

Upvotes: 4

kiran Biradar
kiran Biradar

Reputation: 12742

The below method does exactly without any if condition in for loop.

Idea is just loop till i < SIZE-1 and print the last digit outside of the loop.

int i=0 ;
printf("{");
for (i =0; i < SIZE-1; i++ )
{
    printf("%d, ", arr[i]);
}
printf("%d}", arr[i]);
printf("\n");

Upvotes: 2

user3386109
user3386109

Reputation: 34839

The code needs to treat the first or the last element of the array as a special case. To treat the first element as special, the code should print a comma and space before each number, except for the first element when only the number is printed.

This can be accomplished with a ternary operator. Consider the ternary expression:

i ? ", " : ""

When i is not zero, the expression evaluates to a string that consists of a comma and a space. But when i is zero, the result is an empty string. So i == 0 is the special case.

Here's what the code looks like:

int main(void)
{
    printf("{");
    for (int i = 0; i < SIZE; i++)
    {
        printf("%s%d", i ? ", " : "", arr[i]);
    }
    printf("}\n");
}

Upvotes: -1

萝莉w
萝莉w

Reputation: 177

You can also try this:

#include <stdio.h>
#define SIZE 3
int arr[SIZE] = {1, 2, 3};

int main(void)
{
    printf("{");
    for (int i =0; i < SIZE; i++ )
    {
    printf("%d", arr[i]);
        if(i < (SIZE - 1)){
            printf(", ");
        }
    }
    printf("}");
    printf("\n");
}

Upvotes: -1

aicastell
aicastell

Reputation: 2402

Try this:

#include <stdio.h>
#define SIZE 3
int arr[SIZE] = {1, 2, 3};
int main(void)
{   
    printf("{");
    for (int i =0; i < (SIZE-1); i++ )
    {
        printf("%d, ", arr[i]);
    }
    printf("%d}\n", arr[SIZE-1]);
}

Upvotes: 0

Related Questions