In this article, we are going to understand and implement a simple C program, in which, we need to find the first and last digits of a number. For example, if the given number is 1234, then the first digit is 1, and the last digit is 4. We need to get both the digits.
Find First and Last Digit of a Number in C
Getting the last digit is very easy, we just need to get the remainder while we are dividing the number by 10. Just to get the first digit is a little bit tricky, but still, we can understand and do it.
In the given video, you can find the simple explanation along with the program to find the first and last digits of a number in C.
To get the first digit, we keep on dividing the number by 10, till the number is less than 10, so we are only left with one digit, which is the first digit.
Here is the program to get the first and last digit from the given number in C –
#include <stdio.h>
int main() {
int number, firstDigit, lastDigit;
// Input the number from the user
printf("Enter an integer: ");
scanf("%d", &number);
// Find the last digit (remainder when divided by 10)
lastDigit = number % 10;
// Find the first digit by repeatedly dividing by 10 until it becomes a single digit
firstDigit = number;
while (firstDigit >= 10) {
firstDigit /= 10;
}
// Print the first and last digits
printf("First Digit: %dn", firstDigit);
printf("Last Digit: %dn", lastDigit);
return 0;
}
Output 1 –
Enter an integer: 1234
First Digit: 1
Last Digit: 4
Output 2 –
Enter an integer: 5265254
First Digit: 5
Last Digit: 4