(Review) Write a function w 3 parameters in C (See picture for instructions) Som
ID: 3844658 • Letter: #
Question
(Review) Write a function w 3 parameters in C
(See picture for instructions)
Somehow, my output is NOT 4434 but 4433.
Can you let me know and correct what I am doing wrong?
So far I have this:
#include <stdio.h>
#include <math.h>
int SumSquares(int*array, int row, int column);
int main()
{
int array[2][4]={{23, 12, 14, 3}, {31, 25, 41, 17}};
int row=2;
int column=4;
printf("%d",SumSquares((int*)array, row, column));
return 0;
}
int SumSquares(int*array, int row, int column)
{
int i, j, answer=0;
for(i=0; i<row; i++)
for(j=0; j<column; j++)
answer=answer+pow(*((array+i*column)+j), 2);
return answer;
}
Explanation / Answer
Generally pow function takes two double values and gives a double return type. In your case you are converted double to int so there my data loss in conversion.
Try this one
#include <stdio.h>
#include <math.h>
int SumSquares(int*array, int row, int column);
int main()
{
int array[2][4]={{23, 12, 14, 3}, {31, 25, 41, 17}};
int row=2;
int column=4;
printf("%d",SumSquares((int*)array, row, column));
return 0;
}
int SumSquares(int*array, int row, int column)
{
int i, j, answer=0,val=0;
for(i=0; i<row; i++){
for(j=0; j<column; j++){
val=*((array+i*column)+j);
answer=answer+(val*val);
}
}
return answer;
}
Generally pow function takes two double values and gives a double return type. In your case you are converted double to int so there my data loss in conversion.
Try this one
#include <stdio.h>
#include <math.h>
int SumSquares(int*array, int row, int column);
int main()
{
int array[2][4]={{23, 12, 14, 3}, {31, 25, 41, 17}};
int row=2;
int column=4;
printf("%d",SumSquares((int*)array, row, column));
return 0;
}
int SumSquares(int*array, int row, int column)
{
int i, j, answer=0,val=0;
for(i=0; i<row; i++){
for(j=0; j<column; j++){
val=*((array+i*column)+j);
answer=answer+(val*val);
}
}
return answer;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.