shujaat shujaat - 2 months ago 7
C Question

Finding out the sum of first and the last digit of any number

I want to write a program for finding out the sum of first and the last digit of any number entered through keyboard. For example, I entered 52264. Output must be

5+4 = 9
.

Yes, this is an assignment.

Answer

Well, the last digit's easy enough to figure out, right?

int lastDigit = input % 10;

As for the first digit, I'm not sure about the most efficient way to get that. The first thought that immediately springs to my mind is:

int firstDigit = input;
while (firstDigit >= 10)
{
    firstDigit /= 10;
}

So, with 52264 for example:

int lastDigit = 52264 % 10; // 52264 % 10 = 4

int firstDigit = 52264;
firstDigit /= 10; // 5226
firstDigit /= 10; // 522
firstDigit /= 10; // 52
firstDigit /= 10; // 5 -- less than 10