Programming Hack: Finding the first and the last digit of an integer.

Last digit: One can do this by realizing that the % operator in C returns the remainder. So to find the last digit all one has to do is Last_digit = number%10

First digit: It requires a little bit of ingenuity. We have if we use the \ operator with 10 as the divisor, the quotient is one digit less from the left. So we keep doing it until the number obtained is bigger than 10. First_digit = number; while First_digit > 10 First_digit = First_digit/10

#include<stdio.h>
int main()
{
int N, First_digit, Last_digit;
  N=88937;

  First_digit = N;
  Last_digit = N%10;
  while (First_digit > 10)
     First_digit = First_digit/10;
  printf("%3d %3d %3d",N,First_digit,Last_digit);
  return 0;
}

About Sumant Sumant

I love Math and I am always looking forward to collaborate with fellow learners. If you need help learning math then please do contact me.
This entry was posted in Programming. Bookmark the permalink.

Leave a comment