codescracker
c

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



« C Tutorial C Examples »

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

C Find Sum of Squares of any Two Number

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

// ----codescracker.com----

#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 under Code::Blocks IDE, therefore after successful build and run, here is the sample run:

c program print sum of square two number

Now supply any two number say 4 and 5 and press ENTER key to see the result that will be the sum of square of given two number. If you will square the two number say 4 and 5, then you will get 16 and 25. After summing it up, you will get 16+25 equals 41 as 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 above program:

C Find Sum of Squares of Digits of a Number

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

// ----codescracker.com----

#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 above program:


« C Tutorial C Examples »