- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding sum of first and last digit using divide and modulo operator in C language
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
Advertisements