Extracting and printing the first and last digit of a number – Computer Sir Ki Class Code Learning #CPP#2119    ## Extracting and printing the first and last digit of a number

Using a loop technique and successive division by 10 to extract first and last digit of a given number and then printing it.

## Learning Objectives

• Using successive division by 10 and stopping the loop when the first digit is achieved.

## Source Code

 #include using namespace std; int main() { int n,digit; cout<<"Give a positive integer: "; cin>>n; int nc=n; int last_digit=nc%10; while(nc>=10) { nc=nc/10; } int first_digit=nc; cout<<"First Digit = "<

## Run Output

``````Give a positive integer: 4356
First Digit = 4
Last Digit = 6
``````

## Code Understanding

int nc=n;
We save the input number in a copy so that later operations can be performed on it.

int last_digit=nc%10;
A last digit is simply extracted by modulus division by 10 as we just need the remainder of this division.

while(nc>=10)
Since we need the first digit so we run the loop till only first digit is left which is bound to be less than 10. So the loop continues till >=10.

nc=nc/10;
Here we keep reducing the number by cutting the last digit one by one using integer division by 10.

int first_digit=nc;
We save the number thus achieved in the aptly named variable. This step could be avoided, but sometime neat programming practices require this.

cout<<“First Digit = “<<first_digit<<endl;
cout<<“Last Digit = “<<last_digit<<endl;
As desired we print the first and last digit of the given number.

## Notes

• This approach can help us find any digit from a number.

## Common Errors

• Students  make mistakes in putting right comparison sign here nc>=10. It is important to understand for analysis that we need to find just a single digit so the loop should run till more than single digit is available.

Suggested Filename(s): first-last-dig.cpp

sunmitra| Created: 2-Jan-2018 | Updated: 15-Sep-2018|

×