Google Add

Search

C Program to Calculate the Sum of Digits of a Number

Write a c program to calculate the sum of digits of a number. In this program, we take an input number from a user and then calculate the sum of digits of a number.

Algorithm to calculate the sum of digits of a number


i) Take an input number from a user.

ii) Assign a input number in a variable.

iii) Get the last digit by performing modular division i.e. digit = num % 10.

iv) Take another variable sum and assign the last digit into it i.e. sum = sum + digit.

v) Remove the last digit from number by dividing the number by 10 (num = num / 10).

vi) Repeat step (iii to v) till number becomes 0. After that we will get the sum of the digits of a number.

Find sum of digits of a number using recursion

C Program to Calculate the Sum of Digits of a Number



C Program to Calculate the Sum of Digits of a Number


In this example, we take an input number and calculate the sum of digits of a number.


#include <stdio.h>

int main() {
 
    int num, sum = 0, remainder;
    
    //Input number
    
    printf("Enter a number \n");
    scanf("%d", &num);
    
    
    //If num is greater than zero
    
    while(num > 0) {
    
       /* Find remainder of a a number */
       remainder = num % 10;
    
       /* Add to a sum */
        
       sum = sum + remainder;
       
       /* remove the last digit */
        
       num = num / 10;
    }
    
    
    printf("Sum of digits is %d", sum);
    
    return 0;
}

Output

Enter a number : 234

Sum of digits is 9

Programming questions for beginners

Programming questions on arrays

No comments:

Post a Comment