Write a program that reads a four digit integer and prints the sum of its digits as an output.
#include <stdio.h>
#include <math.h>
int main(){
int four_digit_num, sum = 0, i, positional;
scanf("%d", &four_digit_num);
for(i = 3; i >= 0; i--){
positional = pow(10, i);
sum += four_digit_num / positional;
four_digit_num %= positional;
}
printf("%d\n", sum);
return 0;
}
#include <stdio.h>
int main(){
int four_digit_num, sum = 0, i, positional, j;
scanf("%d", &four_digit_num);
for(i = 3; i >= 0; i--){
positional = 1;
for(j = 0; j < i; j++){
positional *= 10;
}
sum += four_digit_num / positional;
four_digit_num %= positional;
}
printf("%d\n", sum);
return 0;
}
#include <stdio.h>
#include <math.h>
int main(){
int n_digit_num, sum = 0, positional, n;
scanf("%d", &n_digit_num);
n = log10(n_digit_num);
if((n_digit_num >= pow(10, n)) && (n_digit_num < pow(10, n+1))){
for(; n >= 0; n--){
positional = pow(10, n);
sum += n_digit_num / positional;
n_digit_num %= positional;
}
printf("%d\n", sum);
return 0;
}
exit(1);
}