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; }
Comments
Leave a comment