Answer to Question #53185 in C++ for jemal

Question #53185
Write and test the digit() function:
int digit(int n,int k)
This function returns the kth digit of the positive integer n. For example, if n is the integer 29415,
then the call digit(n,0) would return the digit 5, and the call digit(n,2)would return the digit 4. Note
that the digits are numbered from right to left beginning with the “zeroth digit.”
1
Expert's answer
2015-07-01T06:52:41-0400
Code.
#include <iostream>

using namespace std;

int digit(int n, int k) {
for (int i = 0; i < k; i++) {
n /= 10;
}
return n % 10;
}

int main() {
int n = 29415;
cout << "digit(n, 0): " << digit(n, 0) << endl;
cout << "digit(n, 2): " << digit(n, 2);
return 0;
}

Output.
digit(n, 0): 5
digit(n, 2): 4

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS