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

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

  1. Extracting the Last Digit
    The last digit of a number can be obtained using the modulus operator (% 10). For example, the last digit of 1234 is 4, which can be found using 1234 % 10.
  2. 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, for 1234, dividing repeatedly gives 1.

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.

Previous Article

C Program to Generate First N Numbers of Fibonacci Series

Next Article

C Program to Find Sum and Average of User-Defined Number Count

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨