Program to print sum of squares of first n natural numbers using Function

Logic:

  • Enter the number n
  • sum= 12 + 22+ 32 + 4 2+……..+n2

Algorithm

  1. Enter the number as n
  2. Initially assign sum=0
  3. for(i=1;i<=n;i++)
  4. sum=sum + i * i;
  5. Print sum

Time Complexity: O(n)

Space Complexity: O(1)

Program

#include <stdio.h>
int findsum(int n);
int main()
{
    printf("****************************************************************\n");
    printf("****************************************************************\n");
    printf("**  WAP to print sum of squares of first n no using function  **\n");
    printf("**               Created by Sheetal Garg                      **\n");
    printf("**                 Assistant Professor                        **\n");
    printf("**                 Phone No:9467863365                        **\n");
    printf("****************************************************************\n");
    printf("****************************************************************\n");
    int n, sum;
    printf("\nEnter number upto which you want to add\n");
    scanf("%d", &n);
    sum = findsum(n);
    printf("\nsum is %d", sum);
}
int findsum(int n)
{
    int i, s = 0;
    for (i = 1; i <= n; i++)
        s = s + i*i;
    return s;
}

Output 1

****************************************************************
****************************************************************
**  WAP to print sum of squares of first n no using function  **
**               Created by Sheetal Garg                      **
**                 Assistant Professor                        **
**                 Phone No:9467863365                        **
****************************************************************
****************************************************************

Enter number upto which you want to add
4

sum is 30
error: You can only copy the programs code and output from this website. You are not allowed to copy anything else.