Please rewrite the sum_dimensional_array function to use pointer arithmetic instead of array subscripting. (In other words, eliminate the variables i and j and all uses of the [] operator.) Use a single loop instead of nested loops.

Respuesta :

Answer:

The program to this question can be defined as follows:

Program:

#include <stdio.h> //defining header file

#define LEN 3 //defining macro

int sum_dimensional_array(const int arr[][LEN], int n) //defining method

{

   int total = 0; //defining integer variable

   for(const int* x = *arr; x<(*arr+LEN*n);x++) //defining loop to calculate array sum

   {

       total=total+ *x; //calculate sum

   }

   return total; //return value

}

int main() //defining main method

{

int arr[][3]={{6,4,3},{1,2,5}}; //defining integer array that initialise value

int sum=sum_dimensional_array(arr,2); //call the method and hold the value in sum variable

printf("%d\n",sum); // print method value

}

Output:

21

Explanation:

In the above code, first header file then a macro is defined, in the next line method "sum_dimensional_array" is declared, that accepts two parameter that is "arr and n", in which arr is a const array and n is an integer variable.

  • Inside the method, an integer variable total is declared, which is used in the for loop to calculates system define array sum, and returns its value.
  • In the main method, an array arr is declared, which initializes with a value then call the method, and pass the array value as a parameter, and prints its return value.