C/C++ Program to Find the Sum of Cube of Digits of a Number

Write a program to find the sum of cube of digits of a number.

For example,

Input
12345
Output
225
Explaination
13 + 23 + 33 + 43 + 53 = 225

Approach

The solution to this problem is very simple. We will simply using % ( MOD operator ) to read each digit of the input number one by one and store their sum in a temporary variable.

Steps

  1. Let N be the input number.
  2. Initialize a variable sum = 0.
  3. Repeat the following steps while N > 0.
    1. Set temp = N % 10. This stores the rightmost digit of N in temp.
    2. Set N = N / 10. This step removes the rightmost digit of N.
    3. Set sum = sum + temp * temp * temp.
  4. The sum of the cube of digits of the input number is stored in sum.
#include <stdio.h>
#include <math.h>

// returns sum of cube of digits of n
int sum_of_cube(int n) {

	int sum = 0;
	int temp;
	
	while( n > 0 ){
		
		temp = n % 10;	// store rightmost digit of n in temp
		n = n / 10;		// remove rightmost digit of n
		sum = sum + temp * temp * temp;
		
	}
	
	return sum;
	
}

int main() {

	int n;
	printf("Enter a Number: ");
	scanf("%d", &n);

	printf("Sum of the cube of digits of %d = %d", n, sum_of_cube(n));

}

Output

Enter a Number: 12341
Sum of the cube of digits of 12341 = 101

Read

1 thought on “C/C++ Program to Find the Sum of Cube of Digits of a Number”

Leave a Comment

Your email address will not be published. Required fields are marked *