CHIEF CHIEF - 11 months ago 46
C Question

c array on a single line

I have to do a bubble sort with pointers for my class.
I am having trouble with the output
I want every array sort to be on a single line, not individual lines for each element.

Here is an array example that I would want to print.
I flipped the 1 and 9 to ensure that I was printing the proper value, not the location, when it was returning just one number.

[9, 2, 3, 4, 5, 6, 7, 8, 1]

Here is what it prints










How do I get this sample array onto just one line?

#include <stdio.h>
#define MAX 9

int val[] = {9, 2, 3, 4, 5, 6, 7, 8, 1};
int i;

int main(){
for (i = 0; i < MAX; i++
{ printf ("[%d]\n", val[i]);

return (0);
} //end main

Now I have read that you cant output to one line. I keep reading that you need each element to output individually. The prof has the sample output for the bubble pointer showing that all elements of the array remain on the same line. What am I missing?

FYI this is not the bubble sort with pointer. I am just needing help getting this sample array to output properly.
This must be in C, NOT C++, or C#.

Answer Source

I really don't see why you don't just remove the \n, which causes the newline. Then separate out the different parts of your output.

#include <stdio.h>
#define MAX 9

int val[] = {9, 2, 3, 4, 5, 6, 7, 8, 1};
int i;

int main(void){
    for (i = 0; i < MAX; i++) {
      if (i == MAX - 1)
        printf ("%d", val[i]);
        printf ("%d, ", val[i]);

    return (0);
}   //end main

You cannot print the [ in the loop, or else it will print every time. Then, in the loop you want to print a comma unless you are at your last element where no elements should be printed next (if (i == MAX - 1). Finally you print the newline and the closing bracket at the end once the loop finishes. Make note that puts() automatically prints a newline.