Q2. Write a code to find sum of digits of a given number
Sum of digits :- Here we will discuss how we can find the sum of digits in a given number. Let us understand that with the help of an example.
For Example :-
Input:- 3256
Output:- 16
Explanation:- As you can see the given number is 3256 and we have to calculate the sum of digits in the given number, so here we have the following digits 3, 2, 5, 6, and we will sum all these digits -> 3 + 2 + 5 + 6 and the result we get is 16 that will be our output.
Below you will find its algorithm and program.
Sum Of Digits of a number Algorithm
START
Step 1: Get number by user
Step 2: Get the modulus/remainder of the number
Step 3: sum the remainder of the number
Step 4: Divide the number by 10
Step 5: Repeat the step 2 while number is greater than 0.
STOP
Sum Of Digits of a number Program
#include <stdio.h>
int sum_digit(long long num)
{
int sum = 0,rem;
while (num != 0) {
rem=num%10;
num = num / 10;
sum=sum+rem;
}
return sum;
}
// Driver code
int main(void)
{
long long num = 3256;
printf(“Sum Of Digits : %d”,sum_digit(num));
return 0;
}
#include <iostream>
using namespace std;
int sum_digit(long long num)
{
int sum = 0,rem;
while (num != 0) {
rem=num%10;
num = num / 10;
sum=sum+rem;
}
return sum;
}
// Driver code
int main(void)
{
long long num = 3256;
cout << “Sum Of Digits : “
<< sum_digit(num);
return 0;
}
class LFC {
static int sum_digit(int num)
{
int sum = 0,rem;
while (num != 0) {
rem=num % 10;
num = num / 10;
sum=sum+rem;
}
return sum;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int num = 3256;
System.out.print(“Sum Of Digits : ” + sum_digit(num));
}
}
def sum_digit(num):
sum1 = 0
rem = 0
while num != 0:
rem=num%10
num //= 10
sum1=sum1+rem
return sum1
# Driver Code
num = 3256
print (“Sum Of Digits : % d”%(sum_digit(num)))
function sum_digit($num)
{
$sum = 0;
$rem=0;
while ($num != 0)
{ $rem=$num%10;
$num = $num / 10;
$sum=$sum+$rem;
}
return $sum;
}
// Driver code
$num = 3256;
echo “Sum Of Digits : “
. sum_digit($num);
Output
Sum Of Digits : 16
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number