0

Can anyone help, I am stuck on solving this question:

Write a function in C that takes three parameters: the address of a two dimensional array of type int, the number of rows in the array, and the number of columns in the array. Have the function calculate the sum of the squares of the elements.

For example, for the array of nums that is pictured below:

  23  12  14   3

  31  25  41  17

the call of the function might be sumsquares ( nums, 2, 4 ); and the value returned would be 4434. Write a short program to test your function.


So far my program consists of:

#include<stdio.h>
int addarrayA(int arrayA[],int highestvalueA);

int addarrayA(int arrayA[],int highestvalueA)
{
int sum=0, i;
for (i=1; i<highestvalueA; i++)
    sum = (i*i);

return sum;
}

int main( void )
{
int arr [2][4] = {{ 23, 12, 14,  3 },
                 { 31, 25, 41, 17 }};

printf( "The sum of the squares: %d. \n", addarrayA (arr[2], arr[4]) );

return 0;
}

The answer I am receiving is a huge negative number but it should be 4434.

Any help is greatly appreciated!

Chris Tang
  • 567
  • 7
  • 18
Fearphones
  • 19
  • 1
  • 3
  • Which huge negative number? – Pikamander2 Dec 04 '15 at 01:54
  • 1
    You do not pass a 2D array and your functios don't take one either. – too honest for this site Dec 04 '15 at 01:56
  • 2
    You don't use the `arrayA` parameter in your function, which I imagine would be something you should be doing. – Emil Laine Dec 04 '15 at 01:56
  • 2
    I think before asking for help you should try to convince yourself of why your code should work. (Hint: it really doesn't even come close to your description of things.) – mah Dec 04 '15 at 01:59
  • 1
    Hint: *"the call of the function might be `sumsquares( nums, 2, 4 );`"* – user3386109 Dec 04 '15 at 02:11
  • in your addarrayA(arr[2], arr[4]), you're running out of range. thus you're running into unknown memory location. the values in these locations are random. in C/C++ you need to be careful of memory locations and the range of your arrays. – NPToita Dec 04 '15 at 03:02

2 Answers2

2

As you mentioned in question, you need sumsquares( array, 2, 4 ); , but your function don't do that.

See below code:

#include<stdio.h>

int sumsquares(int* arrayA,int row, int column);

int sumsquares(int* arrayA,int row, int column)
{
    int sum=0, i;
    for (i=0; i<row*column; i++)
        sum += (arrayA[i]*arrayA[i]);

    return sum;
}

int main( void )
{
    int arr [2][4] = {{ 23, 12, 14,  3 },
                      { 31, 25, 41, 17 }};

    printf( "The sum of the squares: %d. \n", sumsquares (&arr[0][0], 2, 4) );

    return 0;
}

Output:

The sum of the squares: 4434.
Keshava GN
  • 4,195
  • 2
  • 36
  • 47
-2

We might use this syntax to create a multi-dimensional array in C:

arr = (int **) malloc (( n *sizeof(int *));
Wen Yang
  • 1
  • 1