Introduction
In this tutorial, we will write a C program to find the sum of the first and last digit of a given number. This is a simple yet effective way to practice working with digits in C programming. The task involves extracting the first and last digits from an integer and calculating their sum.
Steps to Find the Sum of First and Last Digit
- Extracting the Last Digit
The last digit of a number can be obtained using the modulus operator (% 10
). For example, the last digit of1234
is4
, which can be found using1234 % 10
. - Extracting the First Digit
To extract the first digit, we divide the number by 10 repeatedly until the number becomes a single-digit number. For instance, for1234
, dividing repeatedly gives1
.
C Program to Find Sum of First and Last Digit
#include <stdio.h>
int main() {
int num, firstDigit, lastDigit, sum;
// Input the number
printf("Enter a number: ");
scanf("%d", &num);
// Finding the last digit
lastDigit = num % 10;
// Finding the first digit
firstDigit = num;
while (firstDigit >= 10) {
firstDigit = firstDigit / 10;
}
// Calculating the sum
sum = firstDigit + lastDigit;
// Displaying the result
printf("Sum of first and last digit is: %d\n", sum);
return 0;
}
Explanation of the C Program
- Input: The program takes an integer as input from the user.
- Last Digit: We calculate the last digit by using the modulus operator.
- First Digit: We divide the number by 10 until it becomes a single-digit number.
- Sum Calculation: Finally, we add the first and last digits and display the result.
Sample Output
Enter a number: 54321
Sum of first and last digit is: 6
Use Cases and Applications
This program is useful in:
- Basic arithmetic problems
- Number manipulation
- Understanding how to work with digits in C
It helps you practice working with loops, arithmetic operations, and input handling.
Conclusion
By writing this C program to find the sum of the first and last digit, you can practice extracting specific digits from a number. This is a basic but essential skill in programming, especially when working with numerical data and user input.