C Program to Find Sum of First and Last Digit Of a Number

How to write a C Program to Find Sum of First and Last Digit Of a Number with an example?.

C Program to Find Sum of First and Last Digit Of a Number

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

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

In this above C Programming example, Number = 2345

Count = log10(Number) = 3
FirstDigit = 2345 / pow(10, 3) = 2345 / 1000 = 2.345 = 2
LastDigit = 2345 % 10 = 5

Sum = 2 + 5 = 7

Program to Find Sum of First and Last Digit Of a Number Example 2

This program will use While Loop to find the First Digit of the user entered value. We already explained the Analysis part in our previous articles. So, Please refer First and Last article to understand the same.

#include <stdio.h>
 
int main()
{
  	int Number, FD, LD, Sm = 0;
 
  	printf("\n Please Enter any Number that you wish  : ");
  	scanf("%d", & Number);
  	
  	FD = Number;
  	
  	while(FD >= 10)
  	{
  		FD = FD / 10;
	}
  	
  	LD = Number % 10;
  	
  	Sm = FD + LastDigit;
	    
	printf(" \n The Sum of First Digit (%d) and Last Digit (%d) of %d =  %d", FD, LD, Number, Sm);
 
  	return 0;
}
 Please Enter any Number that you wish  : 45896
 
 The Sum of First Digit (4) and Last Digit (6) of 45896 =  10

C Program to calculate Sum of First and Last Digit Of a Number using Function

This program to calculate sum of first and last digit is the same as above, but this time we divided the code using the Functions concept.

#include <stdio.h>

int FirDi(int num);
int LstDi(int num); 

int main()
{
  	int Number, First, Last, Sm = 0;
 
  	printf("\n Please Enter any Number that you wish  : ");
  	scanf("%d", & Number);
  	
  	First = FirDi(Number);
  	Last = LstDi(Number);

  	Sm = FirstDigit + LastDigit;
	    
	printf(" \n The Sum of First (%d) and Last (%d) of %d =  %d", First, Last, Number, Sm);
 
  	return 0;
}

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

int LstDi(int num)
{
	return num % 10;
}
 Please Enter any Number that you wish  : 45862
 
 The Sum of First (4) and Last (2) of 45862 =  6