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
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, unsignedint base = 10 )
{
int digit;
if ( base == 0 || 10 < base ) base = 10;
do
{
digit = n % base;
} while ( n /= base );
return digit;
}