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

Learn more about our help with Assignments: C++

## Comments

## Leave a comment