C Program for Sum of First and Last Digit

Written: August 14, 2026 · Updated: August 15, 2026

Digit problems teach modulo arithmetic and loops that peel a number apart safely.

This walkthrough keeps the logic small and readable so you can type it, run it, and then change one input at a time to see what happens.

What you will build

The last digit is n % 10. The first digit is what remains after repeatedly dividing by 10 until fewer than 10 remain.

  • Read a positive integer n
  • last = n % 10
  • While n >= 10, n = n / 10
  • Sum first (n) and last, then print

Working C example

include <stdio.h>

int main(void) {
    int n, first, last, sum;
    printf("Enter a positive integer: ");
    if (scanf("%d", &n) != 1 || n < 0) return 1;
    last = n % 10;
    first = n;
    while (first >= 10) {
        first /= 10;
    }
    sum = first + last;
    printf("Sum of first and last digit = %d\n", sum);
    return 0;
}

Advertisement

How the logic works

Read the program top to bottom: includes and main first, then the statements that change variables, then the print that proves the result.

If your output looks wrong, print the variables before and after the critical lines. That single habit catches most beginner bugs faster than rewriting the whole file.

For a single-digit input, first and last are the same number—confirm your loop handles that.

Advertisement

Keep learning

If this walkthrough on C Program for Sum of First and Last Digit helped, open the code again and change one input or assumption. Small experiments beat rereading the same example.

Want more step-by-step tutorials like this? Browse blog.xqa.io — and tell us which topic you want next.

Advertisement

Previous Article

Find the Maximum Element in a 1D Array in C

Next Article

C Program to Print Star Patterns

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 ✨