# Thread: simple question for a beginner with arrays

1. ## simple question for a beginner with arrays

this is the exercise i am having difficulty with:
Write a function that prints the values stored in an array of doubles containing n elements. The
function prototype is:
void print_array(double x[], int n);
The required format for the output is [elem0 elem1 elem2 ... elemn-1]; that is, a list
of values enclosed in square brackets, with one space between each pair of values. There miust
be no spaces between the '[' and the first value, or between the last value and ']'. Here is an
example: [1.0 5.2 -3.7 4.9].
Write a main function that exercises print_array.

and this is the code i have so far:

Code:
```void print_array (double x[], int n){

int i=0;

for (x[i];i<n;i++){

if (x[0]){
printf("[%d ", x[0]);
}
else if (x[n-1]) {
printf("%d]\n",x[n-1]);
}
else {
printf("%d ", x[i]);
}

}

}```
i believe that my code is correct, but an not sure how to test it. i am having problems with the last part of the problem "Write a main function that exercises print_array."

2. Originally Posted by Student12321
and this is the code i have so far:
You will find it easier to print the '[' and ']' before and after the loop, respectively. Your checks for x[0] is wrong. Your checks should be concerned with the index or with n, not with the value of the elements.

Furthermore, you can simplify the logic by just printing the first element, if it exists, then by printing the remaining elements with the " %d" format string.

Originally Posted by Student12321
i believe that my code is correct, but an not sure how to test it. i am having problems with the last part of the problem "Write a main function that exercises print_array."
This is just a matter of creating an array and calling the function.

3. thanks, im not quite clear, but ill fiddle around with it.

what did you mean at the part i bolded?
Originally Posted by laserlight
You will find it easier to print the '[' and ']' before and after the loop, respectively. Your checks for x[0] is wrong. Your checks should be concerned with the index or with n, not with the value of the elements.

4. Originally Posted by Student12321
what did you mean at the part i bolded?
Suppose x[0] is 0. Then your code will not print '[', because 0 evaluates to false.

EDIT:
Also, to print a double, you should use %f not %d.

5. hello again, i got it working but i have a question to clear up:
how come the first case works here, but the second case does not?
Code:
```    int sum
int i=0;
printf("[");
for (x[i];i<n;i++){

if (i==n-1) {
sum=x[n-1];
printf("%d]\n",sum);
}
else {
sum=x[i];
printf("%d ", sum);
}

}

}```
Code:
```    int sum
int i=0;
printf("[");
for (x[i];i<n;i++){

if (i==n-1) {
printf("%d]\n",x[n-1]);
}
else {
printf("%d ", x[i];
}

}

}```

6. It looks like it should work in both cases, once you fix the syntax errors. By the way, writing x[i] as the first statement of the for loop is pointless.