First and last digit of an integer in a function and putting at reference location – CSKC
Sign In

Search

Solved Problem #CPP#3018    siteicon   siteicon  

Problem Statement - First and last digit of an integer in a function and putting at reference location

Write a c++ program using a function with the following prototype –
void first_last_digit(int n,int first,int last);
In this function pass an integer number as n and then find the first and last digit of n. Then update it on locations first and last passed as reference. Assume values to be passed to demonstrate the working of this function in the main routine.

Solution

TC++ #3018

 

×

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

void first_last_digit(int n,int &first,int &last)
In this function n is the input number and &first and &last are two locations where the computed values will be put
{
last=n%10;
Modulus by 10 will give the remainder which will always be the last number of an integer.

while(n>=10) { n=n/10; }
Till the number is reduced to a single digit number (n>=10) we will keep removing the last number.

first=n;
After all the last numbers are removed and single digit is left, that would be the first number
}

 

int a=12345,first,last;
Here we decide about the number to be tested and will name two locations first and last when the function will put values.

first_last_digit(a,first,last);
a will be passed to this function and location first and last are passed as reference. After the function executes the variables first and last will contain the desired values.

cout<<“First and Last Digit of “<<a<<” are “<<first<<” & “<<last<<endl;
Values will be printed here.

 

Notes

  • Some programmers prefer to return 0 after calling such function to confirm that function did run till the end. Although the values returned are actually put in the reference location.

Common Errors

  • Student forget to put the & sign while passing the reference variable to a function.
  • Sometimes people also put additional & while function call. For example:  first_last_digit(a,&first,&last) is incorrect while calling.


Share

Created: 25-Jan-2018 22:22 | Updated: 29-Nov-2018 19:50|