Write a C++ Program to Find the Sum of the First and Last Digit of a Number with an example. Here, first, we found the first and last digits in a given number. Next, we performed an arithmetic addition on them.
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int number, firstDigit, lastDigit, sum, count;
cout << "\nPlease Enter Number to find Sum of First and Last Digit = ";
cin >> number;
count = log10(number);
firstDigit = number / pow(10, count);
lastDigit = number % 10;
sum = firstDigit + lastDigit;
cout << "\nTotal Number of Digit in a Given Number " << number << " = " << count + 1;
cout << "\nThe First Digit in a Given Number " << number << " = " << firstDigit;
cout << "\nThe Last Digit in a Given Number " << number << " = " << lastDigit;
cout << "\nThe Sum of First and Last Digit of " << number << " = " << sum;
return 0;
}
C++ Program to find Sum of First and Last Digit of a Number Example 2
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int number, firstDigit, lastDigit, sum;
cout << "\nPlease Enter Number to find Sum of First and Last Digit = ";
cin >> number;
for(firstDigit = number; firstDigit >= 10; firstDigit = firstDigit/10);
lastDigit = number % 10;
sum = firstDigit + lastDigit;
cout << "\nThe First Digit in a Given Number " << number << " = " << firstDigit;
cout << "\nThe Last Digit in a Given Number " << number << " = " << lastDigit;
cout << "\nThe Sum of First and Last Digit of " << number << " = " << sum;
return 0;
}
In this C++ example to find the Sum of the First and Last Digit of a Number, we used a while loop to get the first digit.
#include<iostream>
using namespace std;
int main()
{
int number, firstDigit, lastDigit, sum;
cout << "\nPlease Enter Number to find Sum of First and Last Digit = ";
cin >> number;
firstDigit = number;
while(firstDigit >= 10)
{
firstDigit = firstDigit/10;
}
lastDigit = number % 10;
sum = firstDigit + lastDigit;
cout << "\nThe First Digit in a Given Number " << number << " = " << firstDigit;
cout << "\nThe Last Digit in a Given Number " << number << " = " << lastDigit;
cout << "\nThe Sum of First and Last Digit of " << number << " = " << sum;
return 0;
}
C++ Program to calculate Sum of First and Last Digit of a Number using functions
#include<iostream>
using namespace std;
int firstDigitofNumber(int num)
{
while(num >= 10 )
{
num = num / 10;
}
return num;
}
int lastDigitofNumber(int num)
{
return num % 10;
}
int main()
{
int number, firstDigit, lastDigit, sum;
cout << "\nPlease Enter Number to find Sum of First and Last Digit = ";
cin >> number;
firstDigit = firstDigitofNumber(number);
lastDigit = lastDigit = lastDigitofNumber(number);
sum = firstDigit + lastDigit;
cout << "\nThe First Digit in a Given Number " << number << " = " << firstDigit;
cout << "\nThe Last Digit in a Given Number " << number << " = " << lastDigit;
cout << "\nThe Sum of First and Last Digit of " << number << " = " << sum;
return 0;
}