# 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.”

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.”

Expert's answer

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

#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 orderand get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

## Comments

## Leave a comment