Back to Top

Tuesday, 14 April 2015

Begginer's Guide to C++- Chapter 4.1: Digit Extraction

So here we are on yet another “Perfection Phase” Article. We will now learn to extract digits from a number. It is really simple, but since it is important, I will show you exactly how it is done.


Let the number entered by the user be stored in an integer variable named a.


Suppose that we need the sum of all the digits of the number a. Eg- if the number is 123, we want the output to be 1+2+3=6.


To implement the above, we can follow the procedure as described below:


int d, sum=0;   //d will be the extracted digit
while(a!=0)
{d=a%10;   //this expression will get the digit on the one's place.
sum=sum+d;
a=a/10;   //this expression will make the number one digit smaller
}


Let us now look at the process in much more detail, and check out what each step does.
Let the number be 123.

Loop no.
d=a%10
sum=sum+d
a=a%10
1st Iteration
d=3
sum=3
a=12
2nd Iteration
d=2
sum=5
a=1
3rd Iteration
d=1
sum=6
a=0


But some of you might think, how is the value of a equal to 12 and not 12.3 after the first iteration? The answer is that the datatype of a is int. Therefore the compiler only reads the number before the decimal, and any numbers beyond it are simply dropped. Therefore no. 12.3 will now be equal to 12.


Now that you know what digit extraction is, let us proceed to some practice questions.


Q1. Write a program to check whether the number entered by the user is a palindrome or not. (Palindromes are numbers which remain same even when they are reversed. Eg-121)

Q2. Write a program to check whether the n number entered by the user is a Armstrong number or not. (Armstrong numbers are those,  whose sum of cube of digits is equal to the number itself.)

About The Author
Rajat is a coding enthusiast, with an explicit interest in reading and gaming. He is the admin of this blog and is currently working on increasing the reach of the blog. He is called "Dr. Sheldon Cooper" by his coworkers, but extraordinary is the fact that he does not know who Sheldon is! Follow him on .