Problem
What is the C program to obtain the sum of the first and last digit of the number, if a four-digit number is input through the keyboard?
Solution
In this program, we are taking a four-digit number at run time and trying to find the sum of first and last digit of that four-digit number by using the logic −
a=n%10; b=n/1000; result = a + b;
Let’s apply this logic to find sum of first and last digit of four-digit number −
Example
Following is the C program for finding sum of first and last digit by using divide and modulo operator −
#include<stdio.h> main(){ int n,a,b,result; printf("Enter a four digit number: "); scanf("%d",&n); a=n%10; b=n/1000; result = a + b; printf("After adding first and last digit is %d", result); getch(); }
Output
When the above program is executed, it produces the following result −
Enter a four digit number: 2345 After adding first and last digit is 7
Program
Following is the C program for a six-digit number and try to find sum of first and last digit −
#include<stdio.h> main(){ int n,a,b,result; printf("Enter a six digit number: "); scanf("%d",&n); a=n%10; b=n/100000; result = a + b; printf("After adding first and last digit is %d", result); getch(); }
Output
When the above program is executed, it produces the following result −
Enter a six digit number: 346713 After adding first and last digit is 6