Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c program, passing array to function, terminates early

#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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading