This blog is under construction

Wednesday, 10 July 2013

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

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


  #include <stdio.h>
  int main() {
        int num, cube, sum = 0, i = 1;

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

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

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

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:3
  Sum of cubes of first 3 natural numbers is 36



3 comments:

  1. do you want to know how above program works

    What is cube sum program written in c ?
    In this cube sum program , we find cube of individual digit of a number and find their sum .for example: 123 = 1^3 + 2 ^3 + 3^3.
    Cube of individual digit have to be found for that we have to extract each digit .As we know last digit of number can be extract using modulus division (i.e 123%10 = 3 ) , And if we do integer division of given number by 10 , we can get other digit excluding last digit .
    http://onlineclab.blogspot.com/2016/02/cube-sum-program-c.html

    ReplyDelete