C - Write program to implement arithmetic and array functions

Requirements

Implement functions with the prototypes:

double add(double a, double b);        // Returns a+b
double subtract(double a, double b);   // Returns a-b
double multiply(double a, double b);   // Returns a*b
double array_op(double array[], size_t size, double (*pfun)(double,double));

The parameters for the array_op() function are

  • the array to be operated on,
  • the number of elements in the array, and
  • a pointer to a function defining the operation to be applied between successive elements.

When subtract() function is passed in, the function combines the elements with alternating signs.

So for an array with four elements, x1, x2, x3, and x4, it computes the value of x1 - x2 + x3 - x4.

For multiply, it will just be the product of the elements, x1 x x2 x x3 x x4, for example.

Demonstrate the operation of these functions with a suitable version of main().

Demo

#include <stdio.h>

double add(double a, double b);                                         // Returns a+b
double subtract(double a, double b);                                    // Returns a-b 
double multiply(double a, double b);                                    // Returns a*b
double array_op(double array[], size_t size, double(*pfun)(double, double));

int main(void)
{
  double array[] = { 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0 };

  int length = sizeof array / sizeof(double);
  printf("The value of:\n");
  for (int i = 0; i< length; i++)
  {/*w w  w.ja  v  a 2 s  . c o m*/
    printf("%.2lf%s", array[i], (i<length - 1 ? " + " : "\n"));
  }
  printf(" is %.2lf\n", array_op(array, length, add));

  printf("\nThe value of:\n");
  for (int i = 0; i< length; i++)
  {
    printf("%.2lf%s", array[i], (i < length - 1 ? (i % 2 == 0 ? " - " : " + ") : "\n"));
  }
  printf(" is %.2lf\n", array_op(array, length, subtract));

  printf("\nThe value of:\n");
  for (int i = 0; i < length; ++i)
  {
    printf("%.2lf%s", array[i], (i < length - 1 ? " * " : "\n"));
  }
  printf(" is %.2lf\n", array_op(array, length, multiply));
  return 0;
}

// Function to calculate a+b
double add(double a, double b)
{
  return a + b;
}

// Function to calculate a-b
double subtract(double a, double b)
{
  return a - b;
}

// Function to calculate a*b
double multiply(double a, double b)
{
  return a * b;
}

// Function to apply an operation, pfun, between successive pairs of elements
double array_op(double array[], size_t size, double(*pfun)(double, double))
{
  double result = array[size - 1];
  size_t i = 0;
  // Work from last to first to accommodate alternating signs for subtract
  for (i = size - 1; i > 0; i--)
    result = pfun(array[i - 1], result);
  return result;
}

Result

Related Exercise