Write a C program to evaluate the following series. The series contains the sum of the square of numbers from 1 to ‘n’. Store results of each term in an array.
Calculate the value of ‘ S ‘ using an array.
S = 1^2 + 2^2 + 3^2 + 4^2 + —— n^2
= [ 1, 4, 9, 16, ——– n^2 ]
Suppose n = 4,
then S = 1^2+2^2+3^2+4^2;
S = 1+4+9+16;
S = 30.
#include<stdio.h> #include<stdlib.h> int main() { int Index,*IntArray,Sum,Val,n; printf("Array size : "); scanf("%d",&n); IntArray = (int*)malloc(sizeof(int)*n); Sum = 0; for(Index = 0,Val = 1;Index < n;Index++,Val++) { IntArray[Index] = Val*Val; Sum = Sum + IntArray[Index]; if(Index < n-1) printf("%d + ",IntArray[Index]); } printf("%d = %d\n",IntArray[n-1],Sum); return 0; }
Output
Array size : 6 1 + 4 + 9 + 16 + 25 + 36 = 91