Home > OS >  c program, passing array to function, terminates early
c program, passing array to function, terminates early

Time:11-10

#include <stdio.h>
#include <math.h>

void abs_table (double x[], int size);

int main (void) {

        int size, index;
        printf("Enter number of elements: ");
        scanf("%d", &size);

        double x[size], element;

        for (index = 0; index < size; index  ) {

                printf("Enter x[%d]: ", index);
                scanf("%lf", &element);
                x[index] = element;

        }

        void abs_table (double x[], int size);

        return 0;

}

void abs_table (double x[], int size) {

        int index;

        double y[size];

        for (index = 0; index < size; index  ) {

                y[index] = fabs(x[index]);

                printf("%lf\t%lf\n", x, y);

        }
}

program to read in array values and display the absolute value of each element using a void function.

program terminates after storing values into array x. void function does not display.

CodePudding user response:

  1. Call abs_table() instead of declaring it in main().
  2. Index x and y in abs_table() print statement. As you don't use y other than to print the current value eliminate it.
  3. (minor) Move main() after function so you don't need the declaration.
  4. (minor) Minimize scope of variables.
  5. (minor, not fixed) If your size argument is before x, then you can document their relationship void abs_table(int size, double x[size]).
  6. (minor. not fixed) prefer unsigned variables (index, size etc).
  7. (not fixed) check if scanf() returns 1 in your code otherwise the values size and x[index] may be undefined.
#include <stdio.h>
#include <math.h>

void abs_table (double x[], int size) {
    for (int index = 0; index < size; index  ) {
        printf("%lf\t%lf\n", x[index], fabs(x[index]));
    }
}

int main (void) {
    int size;
    printf("Enter number of elements: ");
    scanf("%d", &size);
    double x[size];
    for (int index = 0; index < size; index  ) {
        printf("Enter x[%d]: ", index);
        scanf("%lf", &x[index]);
    }
    abs_table(x, size);
    return 0;
}

Here is an example run;

Enter number of elements: 3
Enter x[0]: -1.2
Enter x[1]: 1.3
Enter x[2]: -100
-1.200000       1.200000
1.300000        1.300000
-100.000000     100.000000
  •  Tags:  
  • c
  • Related