C Program to Find First and Last Digit Of a Number

How to write a C Program to Find 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.

/* C Program to Find First and Last Digit Of a Number */
 
#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 Program to Find First and Last Digit Of a Number, Number = 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

Program to Find 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 First Digit and Last Digit article in C Programming to understand the same.

/* C Program to Find First and Last Digit Of a Number using Function */
 
#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;
}

C first and last digit 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