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