C++ Program to Find Sum of Squares of Digits of a Number

This article provides some programs in C++ that find and prints the sum of squares of digits of a given number. The program is created in following ways:

• Using while loop
• Using for loop

For example, if given number is 32041, then the result will be calculate as:

32041 = 32 + 22 + 02 + 42 + 12
= 9 + 4 + 1 + 16 + 1
= 31

Sum of Squares of Digits of a Number using while Loop

The question is, write a C++ program that receives a number from user to find and print the sum of squares of its digits. The program given below is its answer:

#include<iostream>

using namespace std;
int main()
{
int num, rem, sq, sum=0;
cout<<"Enter a Number: ";
cin>>num;
while(num>0)
{
rem = num%10;
if(rem==0)
sq = 1;
else
sq = rem*rem;
sum = sum + sq;
num = num/10;
}
cout<<"\nSum of squares of all digits = "<<sum;
cout<<endl;
return 0;
}

The initial output produced by above C++ program on finding and printing the sum of squares of digits of a number entered by user is shown in the snapshot given below:

Now supply a number say 32041 as input and press ENTER key to find and print sum of squares of all digits of 32041 as shown in the snapshot given below:

Find Sum of Squares of Digits of Number using for Loop

This is the last program, created using for loop that does the same job as of previous program. Also this program produces exactly same output as of previous one.

#include<iostream>

using namespace std;
int main()
{
int num, rem, sq, sum;
cout<<"Enter a Number: ";
cin>>num;
for(sum=0; num>0; num=num/10)
{
rem = num%10;
if(rem==0)
sq = 1;
else
sq = rem*rem;
sum = sum + sq;
}
cout<<"\nSum of squares of all digits = "<<sum;
cout<<endl;
return 0;
}

C++ Online Test

« Previous Program Next Program »