Thursday, April 16, 2009

Program to sum of the digits of a five digit number.

Exercise 8
If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits.
(Hint: Use the modulus operator ‘%’)
Solution:

/* Program to sum of the digits of a five digit number */
#include<stdio.h>
#include<conio.h>


void main()
{
int num, sum=0,m=0,i;
printf(“Enter a five digit number: ”);
scanf(“%d”, &num);
/* Logical part to sum up the digits */
for(i=1; i<=5; i++)
{
m=num%10;
sum=sum+m;
num=num/10;
}
printf(“\nTherefore the sum of the digits of the given number is = %d”, sum);
getch();
}

This program is also a simple one, let us under stand the logical part of the program with the help of the truth-table.
Let the value of num=57349
initial condition m = 0 sum = 0 num = 57349
when i = 1 m = 57349 % 10 = 9 sum = 0 + 9 = 9 num = 57349/10 = 5734
when i = 2 m = 5734 % 10 = 4 sum = 9 + 4 = 13 num = 5734/10 = 573
when i = 3 m = 573 % 10 = 3 sum = 13 + 3 = 16 num = 573/10 = 57
when i = 4 m = 57 % 10 = 7 sum = 16 + 7 = 23 num = 57/10 = 5
when i = 5 m = 5 % 10 = 5 sum = 23 + 5 = 28 num = 5/10 = 0
Module operator(%) find outs the remainder, and as num is taken as an integer variable so, when divided by 10 the decimal part is lost or do not comes into the scenario. And in this program loop is used, which we still haven’t studied, in the next blog we will read about it. It is just used for the sake of simplicity, otherwise we have to repeat the steps by writing again and again.
Therefore we get, at the end of the program, sum = 28 (5+7+3+4+9=28)
The output of the program is as follows:
Enter a five digit number: 57349
Therefore the sum of the digits of the given number is = 28

No comments:

Post a Comment

Please give your valuable comments or queries if you fell its helpful or if you like the contents of the site. Thanks...