Extracting and printing the first and last digit of a number – CSKC
Sign In

Search

Code Learning #CPP#2119    siteicon   siteicon  

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

TC++ #2119

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

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



Share

Created: 2-Jan-2018 22:38 | Updated: 15-Sep-2018 12:45|