C Program to Find First and Last Digit Of a Number

Write a C Program to Find the First and Last Digit Of a Number with an example.

C Program to Find First and Last Digit Of a Number

This program allows the user to enter any number. And then, it is going to find the First Digit and the Last Digit of the user-entered value.

#include <stdio.h>
#include <math.h>
 
int main()
{
  	int Number, FirstDigit, Count, LastDigit;
 
  	printf("\n Please Enter any Number that you wish  : ");
  	scanf("%d", & Number);
  	
  	Count = log10(Number); 	
  	FirstDigit = Number / pow(10, Count);
  	
  	LastDigit = Number % 10;
	    
	printf(" \n The First Digit of a Given Number %d =  %d", Number, FirstDigit);
	printf(" \n The Last Digit of a Given Number %d =  %d", Number, LastDigit);
 
  	return 0;
}
C Program to Find First and Last Digit Of a Number 1

Within this C Program to Find the First and Last Digit Of a Number, the value = 1234

Count = log10(Number) – This will return the total number of digits in a number -1

Count = 3

FirstDigit = 1234 / pow(10, 3) = 1234 / 1000 = 1.234 = 1

LastDigit = 1234 % 10 = 4

C Program to Find the First and Last Digit Of a Number using Function

This program to find the first and last digit is the same as above, but this time we divided the code using the Functions concept. We have already explained the Analysis part in the previous articles. So, Please refer to First Digit and Last Digit articles in this Programming to understand the same.

#include <stdio.h>

int First_Digit(int num);
int Last_Digit(int num); 

int main()
{
  	int Number, FirstDigit, LastDigit;
 
  	printf("\n Please Enter any Number that you wish  : ");
  	scanf("%d", & Number);
  	
  	FirstDigit = First_Digit(Number);
  	LastDigit = Last_Digit(Number);

	printf(" \n The First Digit of a Given Number %d =  %d", Number, FirstDigit);  
  	printf(" \n The Last Digit of a Given Number %d =  %d", Number, LastDigit);
 
  	return 0;
}

int First_Digit(int num)
{
	while(num >= 10)
	{
		num = num / 10;
	}
	return num;
}

int Last_Digit(int num)
{
	return num % 10;
}

output.

 Please Enter any Number that you wish  : 987564
 
 The First Digit of a Given Number 987564 =  9 
 The Last Digit of a Given Number 987564 =  4