Saturday 22 September 2018

Sum of the digit of a multi-digit number in C++

Sum of digits of a multi-digit number

The mod(%) operator is used to extract the remainder from a division operation.
 E.g.  27%5=2
In this example, the mod operator gives 2. This is because remainder obtained is 2 when 27 is divided by 5.

When any number is divided by 10 and its remainder is extracted then we obtain the last digit of the number.E.g. 29%10=9, here we obtain 9 the last digit of 29.

The slash(/) operator is used to perform arithmetic division.E.g. 100/20=5 which is a normal division.

When int a= 29/10 ;

Actually, the answer is 2.9 but the value is stored as an integer(int). This will neglect the decimal part leaving 2 as the answer because int can't store float(decimal) data type. We can remove the last digit of a multi-digit number by dividing it by 10 and storing it in int data type.


Write a program in C++ to input a multi-digit number and display the sum of the digits.


We will input a multi-digit number from the user. We will use the mod(%) operator to extract the last digit of the number. The last digit is added to a new variable. Then the last digit is removed by using the slash(/) operator. This operation is performed until the multi-digit number is reduced to zero. The while loop will be terminated when the multi-digit number is reduced to zero.
While loop is an iteration control structure.

The syntax of while loop:

while(condition)
{
statement 1;
statement 2;
.
.
.
}


Program


#include<iostream.h>
#include<conio.h>
void main()
{
int a,b=0,sum=0;
clrscr();
cout<<"Enter a multidigit number=";
cin>>a;
while(a!=0)
{
b=a%10;                                                        //Extraction of last digit of number
sum=sum+b;                                                  //Addition of last digit to new variable
a=a/10;                                                          //Removal of last digit of multi digit number
}
cout<<"\nThe sum of the entered number is="<<sum;
getch();
}

Output


Sum calculation of digits of a multi-digit number
DISPLAYING  SUM OF DIGITS OF MULTI DIGIT NUMBER








Explanation


In the program, the input is 4974 which is stored in a. The first statement inside while loop extracts last digit (i.e. 4). The second statement then stores the last digit (i.e. 4) in sum. After storing, the third statement discards the last digit i.e. 4 and a is updated. This process continues till the value of a is reduced to zero. Our required answer is stored in sum which is later displayed on the screen. 







No comments:

Post a Comment