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

In this tutorial, we will learn how to create a program in C that will find and print the sum of squares of any two numbers and also how to find and print the sum of squares of digits of any given number given by the user at run-time.

C Find the sum of any two numbers' squares

Let's first create a program in C that will ask the user to enter any two numbers to find and print the sum of the square of the given two numbers.

#include<stdio.h>
#include<conio.h>
int main()
{
    int num1, num2, sqr1, sqr2, sum;
    printf("Enter any two numbers: ");
    scanf("%d%d", &num1, &num2);
    sqr1 = num1*num1;
    sqr2 = num2*num2;
    sum = sqr1 + sqr2;
    printf("Sum of their square = %d", sum);
    getch();
    return 0;
}

As the program was written in the Code::Blocks IDE, here is the sample run after a successful build and run:

c program print sum of square two number

Now supply any two numbers, say 4 and 5, and press the ENTER key to see the result, which will be the sum of the square of the given two numbers. If you square two numbers, say 4 and 5, you will get 16 and 25. After summing it up, you will get 16 + 25 = 41 as a result. Here is the second snapshot of the sample run:

sum of square of two number c

Here are some of the main steps used in the above program:

Find the sum of the squares of a number's digits in C

Now let's create a program that will ask the user to enter any number to find and print the sum of the squares of its digits. That is, if the user enters 342 as input, the program will calculate the sum of the squares of its digits, which is (3*3) + (4*4) + (2*2), or 9+16+4 or 29. Let's take a look at the program:

#include<stdio.h>
#include<conio.h>
int main()
{
    int num, rem, sum=0;
    printf("Enter any number: ");
    scanf("%d", &num);
    while(num>0)
    {
        rem = num%10;
        sum = sum + rem*rem;
        num = num/10;
    }
    printf("\nSum of Square of Digits = %d", sum);
    getch();
    return 0;
}

Here is the final snapshot of the sample run:

c find sum of square of digit

Here are some of the main steps used in the above program:

C Quiz


« Previous Program Next Program »


Liked this post? Share it!