C program to find the sum of first and last digit of any number

Write a C program to enter any number and find the sum of first and last digit of the number using for loop. How to find sum of first and last digit of any number in C programming using loop. Calculating sum of first and last digit of any number in C.

Example:
Input number: 1234
Output sum of first and last digit: 5

Required knowledge

Basic C programming, For loop

Before moving on to this program it is highly recommended that you must have know how to find first and last digit. If not please first see how to find first and last digit of any number then continue to this program as this program just adds the result of program I mentioned.

Program to find sum of first and last digit

/**
 * C program to find sum of first and last digit of a number
 */

#include <stdio.h>

int main()
{
    int i, n, sum=0;

    /* Reads a number from user */
    printf("Enter any number to find sum of first and last digit: ");
    scanf("%d", &n);
    
    /* Checks whether the number is greater than 2 digits */
    if(n>10) 
    {
        /* Adds last digit to sum */
        sum += n % 10; 
    }

    /* Finds the first digit by dividing n by 10 until first digit is left */
    while(n>=10)
    {
        n = n / 10;
    }

    /* Adds first digit to sum */
    sum += n; 

    printf("Sum of first and last digit = %d", sum);

    return 0;
}


Output
X
_
Enter any number to find sum of first and last digit: 1234
Sum of first and last digit = 5

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

1 comment: