Home > Net >  How to remove comma if a element inside the array is negative?
How to remove comma if a element inside the array is negative?

Time:12-04

for (int i = 1;  i <= size; i  )
{
    printf("Enter element %d: ", i);
    scanf("%d", &array[i]);
    if (array [i] < 0)
        break;
    
}
printf("[");
for (int i = 1; i <= size; i  )
{
    
    if (array[i] < 0)
        break;
    printf("%d", array[i]);
       
}
printf("]");

The output of the code is this

Enter size: 10
Enter element 1: 6
Enter element 2: 8
Enter element 3: 23
Enter element 4: -2
[6,8,23,]

And the professor is expecting it to be this

Enter size: 10
Enter element 1: 6
Enter element 2: 8
Enter element 3: 23
Enter element 4: -2
[6,8,23]

CodePudding user response:

printf("[");
for (int i = 1; i <= size; i  )
{
    if (i != 1 && array[i] >= 0)
        printf(",");
    if (array[i] < 0)
        break;
    printf("%d", array[i]);
}
printf("]");

CodePudding user response:

The task is not to remove the comma. The task is to print the comma only when needed.

Can be done in several ways. Here is one:

printf("[");
for (int i = 1; i <= size; i  )
{
    
    if (array[i] < 0)
        break;
    if (i == 1)
        printf("%d", array[i]);  // For index 1 don't print a comma
    else
        printf(",%d", array[i]); // For all others start with a comma
       
}
printf("]");

Here is another:

printf("[");
// Handle index one before the loop
if (size >= 1 && array[1] >= 0)
{
    printf("%d", array[1]);  // No comma printed
}
for (int i = 2; i <= size && array[i] >= 0; i  )
{
    printf(",%d", array[i]);  // Print comma before element
}
printf("]");

BTW: Array indexing normally starts from zero instead of one.

  • Related