To compute the square root of the sum of the squares of an array elements in C

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: To compute the square root of the sum of the squares of an array elements in C

To show: How to use some math functions available in standard C library implemented using an array type variable

 

 

// Program to compute the square root of the sum of an array elements

#include <stdio.h>

#include <math.h>

// define constants

#define m 4

#define n 5

 

int main(void)

{

int i, j;

int x[m][n]={{4,5,6,2,12},{10,25,33,22,11},{21,32,43,54,65},{3,2,1,5,6}};

double sum2 = 0.0, result;

 

// outer for loop, read row by row...

for(i=0; i<m; i++)

{// inner for loop, for every row, read column by column

for(j=0; j<n>0)

// do the square of the array elements and then sum up...

sum2 = sum2 + pow(x[i][j], 2);

}

 

// assign the result to variable result, do the square root of the previous result

result = sqrt(sum2);

}

 

// some prompt and printing the result...

printf("\nFirst, summing up all the arrays' element");

printf("\nThe given array has 4 x 5 in size,\n");

printf("\nThe sum is = %f", sum2);

printf("\n\nNext, square root the sum");

printf("\nThe answer is = %f\n", result);

 

return 0;

}

 

Output example:

 

First, summing up all the arrays' element

The given array has 4 x 5 in size,

The sum is = 13174.000000

Next, square root the sum

The answer is = 114.778047

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index