Find the sum of first and last digit for a number using C language

In C programming, finding the sum of the first and last digit of a number involves extracting these digits using modulus and division operations. The last digit is obtained using modulus 10, while the first digit is found by repeatedly dividing the number by 10.

Syntax

int lastDigit = number % 10;
while(number > 9) {
    number = number / 10;
}
int firstDigit = number;
int sum = firstDigit + lastDigit;

Algorithm

The algorithm to find the sum of first and last digit is as follows −

START
Step 1: Declare number, sum, firstDigit, lastDigit variables
Step 2: Read a number at runtime
Step 3: Extract last digit using lastDigit = number % 10
Step 4: Extract first digit by dividing number by 10 until single digit remains
Step 5: Calculate sum = firstDigit + lastDigit
Step 6: Print the sum
STOP

Example

Following is the C program to find the sum of first and last digit for a number −

#include <stdio.h>

int main() {
    int number, originalNumber, firstDigit, lastDigit, sum;
    
    printf("Enter a number: ");
    scanf("%d", &number);
    
    originalNumber = number;
    
    // Extract last digit
    lastDigit = number % 10;
    
    // Extract first digit
    while(number > 9) {
        number = number / 10;
    }
    firstDigit = number;
    
    // Calculate sum
    sum = firstDigit + lastDigit;
    
    printf("Number: %d<br>", originalNumber);
    printf("First digit: %d<br>", firstDigit);
    printf("Last digit: %d<br>", lastDigit);
    printf("Sum of first and last digit: %d<br>", sum);
    
    return 0;
}
Enter a number: 1242353467
Number: 1242353467
First digit: 1
Last digit: 7
Sum of first and last digit: 8

Example: Using Function

Here's an alternative approach using a separate function −

#include <stdio.h>

int sumFirstLastDigit(int num) {
    int lastDigit = num % 10;
    
    while(num > 9) {
        num = num / 10;
    }
    int firstDigit = num;
    
    return firstDigit + lastDigit;
}

int main() {
    int number, result;
    
    printf("Enter a number: ");
    scanf("%d", &number);
    
    result = sumFirstLastDigit(number);
    
    printf("Sum of first and last digit of %d is: %d<br>", number, result);
    
    return 0;
}
Enter a number: 5678
Sum of first and last digit of 5678 is: 13

Key Points

  • The modulus operator % extracts the last digit efficiently
  • Integer division by 10 removes the rightmost digit
  • The loop continues until only the first digit remains
  • This method works for both positive and negative numbers (with slight modification for negatives)

Conclusion

Finding the sum of first and last digits is a fundamental operation in C that demonstrates the use of modulus and division operators. This technique is useful in various mathematical computations and digit manipulation problems.

Updated on: 2026-03-15T13:20:49+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements