Sum of first and last digit of a four digit number
If a four-digit number is input through the keyboard, write a program in C to obtain the sum of the first and last digit of this number.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
long int num;
int sum = 0;
printf("Enter a four digit number\t:");
scanf("%ld", &num);
sum = (num%10) + (num/1000);
printf("\nSum of first and last digit = %ld",sum);
getch();
}
Output
Enter a four digit number :9438
Sum of first and last digit = 17
Explanation
A four digit number is taken as an input from the user in the variable named 'num'. %ld is the format specifier used for long int data type. A variable named 'sum' is used to carry the sum of first and last digit of the number. sum is initialized to 0.
For example, if num = 9438
then, num % 10 = 9438 % 10 = 8
num = 9438
then, num / 1000 = 9438 / 10 = 9
So, the statement
calculates the sum of first and last digit of the number.
num % 10
operation extracts the digit of unit place i.e. last digit
For example, if num = 9438
then, num % 10 = 9438 % 10 = 8
num / 1000
operation extracts the first digit of the number.
num = 9438
then, num / 1000 = 9438 / 10 = 9
So, the statement
sum = (num%10) + (num/1000);
calculates the sum of first and last digit of the number.