#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:
- Call
abs_table()
instead of declaring it inmain()
. - Index x and y in
abs_table()
print statement. As you don't usey
other than to print the current value eliminate it. - (minor) Move main() after function so you don't need the declaration.
- (minor) Minimize scope of variables.
- (minor, not fixed) If your size argument is before x, then you can document their relationship
void abs_table(int size, double x[size])
. - (minor. not fixed) prefer unsigned variables (index, size etc).
- (not fixed) check if
scanf()
returns 1 in your code otherwise the valuessize
andx[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