Fix my Function to find first digit, last digit and number of digits in integer.

Beginning programmer and struggling to understand the concepts. We have to create a function that finds the first and last digits of an integer and the number of digits in an integer. Basically this is the first part of my code and i tried to write it so itd take the number and divide it by 10 until its between one and nine and i would have the first digit.

Code:
#include <iostream>
using namespace std;

int first_digit (int n)
{
    int x;
    do
          {
          int x = n/10;
          }
      while (n >= 9);
      return x;
}

int main()
{int input;
cout << "Please enter a number: " << endl;
cin >> input;
cout << "The first digit is " << endl;
cout << first_digit (input) << endl;
system ("pause");
return 0;
}


using dev c++ it compiles alright but when I run it and enter a number it just says "The first digit is____" without actually outputting anything. I really don't understand why it doesn't work or how im supposed to make it work
1
2
3
4
5
6
7
8
9
10
11
12
int first_digit( int n )
{
    const int base = 10;
    int digit;

    do
    {      
          digit = n % base;
    } while ( n /= base );

    return digit;
}
Last edited on
Thanks for the help worked perfectly!
Could you elaborate what you did here?
          digit = n % base;
    } while ( n /= base );

I don't quite understand why this works but my old code didn't
The operator % produces the remainder of a division.
n /= base; is equivalent to n = n / base;
Last edited on
It would be even better to rewrite the function the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
int first_digit( int n, unsigned int base = 10 )
{
    int digit;

    if ( base == 0 || 10 < base ) base = 10;

    do
    {      
          digit = n % base;
    } while ( n /= base );

    return digit;
}
Last edited on
Topic archived. No new replies allowed.