Write a C Program to Find Out the Addition of a Number ~ CodeTextPro - CodeTextPro | Free Web Tutorial

Codetextpro Provides free Web tutorial, HTML, CSS, C, C++, Java, JavaScript, PHP, MySql, Python, Program, Programming Notes, Programming Questions and more.

Programming

Tuesday, January 8, 2019

Write a C Program to Find Out the Addition of a Number ~ CodeTextPro


Find Sum of a Digit


Introduction 

In the following  C  program, we have to find the addition of a number or digit given by the user.
Like, if the user enters 786 then the result is 786=7+8+6=21.



In mathematics, the digit sum of a given integer is the sum of all its digits (e.g.: the digit sum of 84001 is calculated as 8+4+0+0+1 = 13). Digit sums are most often computed using the decimal representation of the given number, but they may be calculated in any other base; different bases give different digit sums, with the digit sums for binary being on average smaller than those for any other base.

Algorithm:


Step 1:  START
Step 2:  READ N
Step 3:  [INITIALIZE] SUM=0
Step 4:  REPEAT STEPS 4 TO 7 WHILE(N!=0)
Step 5:  SET   REM=N%10
Step 6:  SET   SUM = SUM+REM
Step 7:  SET   N=N/10
Step 8:  PRINT SUM
Step 9:  STOP


Program to Find Sum of a Digit:


#include<stdio.h>
#include<conio.h>
main()
{
int n, rem, sum=0;
printf("\n Enter The Number:");
scanf("%d",&n);
while(n!=0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
printf("\n Sum of the value is: %d",sum);
getch();

}


Input:



We Have To Check the Program using the following input-
⦁1st  case by  giving  input  as  175


⦁2nd  case by  giving  input  as  965

Output:

1st Case:


2nd Case:



Discussion:

If efficiency is not a concern computing the sum of a digit through the algorithm is successively done.


First, we initialized sum=0. We check the digit in a while loop to confirm that if the number is 0 or not, then we store the remainder of n in rem, after that, we store the addition of a reminder and addition in a sum which is previously initialized with 0. Then the number given by the user is divided by 10 and store it in n. After the procedure, we get our expected result.

No comments:

Post a Comment