Sum of Digits of a Five Digit Number Discussions | C | HackerRank

Sum of Digits of a Five Digit Number

  • + 0 comments
    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    #include <stdlib.h>
    
    int main() {
    	
        int n;
        scanf("%d", &n);
        //Complete the code to calculate the sum of the five digits on n.
        
        int digits[5] = {};
        int sum = 0;
        float exp = 10000;
        
        for(int i = 0; i < 6; i++){
            digits[i] = n / exp;
            n = n - digits[i] * exp;
            exp /= 10;
        }
        
        for(int j = 0; j < 6; j++){
            sum += digits[j];
        }
        
        printf("%d", sum);
        
        return 0;
    }