Program to find out the sum of squares of natural numbers


Default
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Write a program to find out the sum of squares of natural numbers
// Ex: 4 -> 30; 10 -> 385

#include<stdio.h>
int main(){
    int num;
    printf("Enter a number to find sum of squares upto that number:");
    scanf("%d",&num);
    while(num<=0){
        printf("Please enter only a positive integer: ");
        scanf("%d",&num);        
    }
    // calculating sum of squares
    int i=1;
    printf("\n");
    if(num<=4){
        while(i<num){
            printf("%d^2+",i);      
            i++;
        }
        printf("%d^2\n",i);
    }
    else{
        printf("1^2+2^2+...+%d^2+%d^2\n",num-1,num);
    }
    long long int sum;
    sum = (num/6.0)*(num+1)*(2*num+1);
    printf("Sum of squares of natural numbers upto n is: %lld",sum);
 getch();
}

No comments:

Post a Comment