This blog is under construction

Wednesday, 10 July 2013

C program to find the sum of squares of first n natural numbers

Write a C program to find the sum of squares of first n natural numbers.


  #include <stdio.h>

  int main() {
        int num, square, sum = 0, i = 1;

        /* get the input value for n from user */
        printf("Enter the value for n:");
        scanf("%d", &num);

        /* calculate the square of 1st n natural numbers */
        while (i <= num) {
                square = i * i;
                sum = sum + square;
                i++;
        }

        /* print the sum of square of first n natural nos */
        printf("Sum of squares of first %d natural"
                        " numbers is %d\n", num, sum);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:10
  Sum of squares of first 10 natural numbers is 385



No comments:

Post a Comment