
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum the Digits of a Given Number in C
The calculation of the sum of the digits of a number in a single statement means that only one line of code will be doing the addition operation. The addition operation should not extend more than one statement.
In this article, we have a number and our task is to calculate the sum of the digits of the number in a single statement in c. Here is a list of approaches:
Using for Loop
This approach uses a for loop to calculate the digit sum in one statement. The for loop continues till num reaches 0.
- The num % 10 finds the last digit of the number.
- Then we add the last digit each time and store it in the variable sum.
- Then, we remove the last digit of the number by dividing it by 10.
Example
Here is an example of implementing the above-mentioned steps to add digits of a number in a single statement using a for loop:
#include <stdio.h> int main() { int num = 534, sum = 0; for(; num; sum += num % 10, num /= 10); printf("Sum of digits of the number is: %d", sum); return 0; }
The output of the above code is given below:
Sum of digits of the number is: 12
Using Recursive Function
You can use a recursive function to calculate the sum of digits of the number in a single statement.
- The num % 10 is used for finding the last digit of the number.
- The sum() function is recursively called to remove the last digit of the number.
- Then, we add all the last digits of the number from step 1 with the digit received after step 2 at the end of the recursion.
Example
Here is an example of a recursive approach to get the sum of digits of number in a single statement:
#include <stdio.h> int sum(int num) { return num ? (num % 10 + sum(num / 10)) : 0; } int main() { int num = 534; printf("Sum of digits of the number is: %d", sum(num)); return 0; }
The output of the above code is given below:
Sum of digits of the number is: 12