In this tutorial, we will learn, how to find the sum of the first and last digit of a number in C. We will see two examples with different approaches. Before that, you should have knowledge of the following topics in C.
C Program to Find Sum of First and Last Digit of any Number using loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <stdio.h> int main() { int num, sum = 0, firstDigit, lastDigit; printf("Enter the Number: "); scanf("%d", &num); // last digit of a number lastDigit = num % 10; //first digit by dividing n by 10 until n greater then 10 while (num >= 10) { num = num / 10; } firstDigit = num; //Calculate sum of first and last digit sum = firstDigit + lastDigit; printf("Sum of first and last digit of entered Number: %d", sum); return 0; } |
Output:
Enter the Number: 325
Sum of first and last digit of entered Number: 8
Now if you enter a number with only one digit, the program will take that single digit as a firstDigit
as well as lastDigit
and add them both as shown below.
Enter the Number: 2
Sum of first and last digit of entered Number: 4
C Program to Find Sum of First and Last Digit of any Number without using loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <stdio.h> #include <math.h> int main() { int num, sum = 0, firstDigit, lastDigit, digit; printf("Enter the Number: "); scanf("%d", &num); // last digit of a number lastDigit = num % 10; //total number of digit - 1 digit = (int) log10(num); //first digit firstDigit = (int)(num / pow(10, digit)); //Calculate sum of first and last digit sum = firstDigit + lastDigit; printf("Sum of first and last digit of entered Number = %d", sum); return 0; } |
Output:
Enter the Number: 964
Sum of first and last digit of entered Number: 13
Note: log10() is a mathematical function present in math.h header file. It returns the log base 10 value of the passed parameter to log10() function.