The program to calculate the sum of digits in C can be implemented using loops and mathematical operations.
Algorithm for Sum of Digits
To write a C program to find the sum of digits, the following algorithm can be used:
-
Step 1: Get a number from the user
-
Step 2: Take the modulus/remainder of that number
-
Step 3: Add the remainder to the total sum
-
Step 4: Divide the number by 10
-
Step 5: Repeat step 2 until the number is greater than 0.
👇点击领取👇
👉C语言知识资料合集
Let’s take a look at the program for sum of digits in C.
#include <stdio.h>
int main() { int n, sum = 0, m; printf("请输入一个数字:"); scanf("%d", &n);
while (n > 0) { m = n % 10; sum = sum + m; n = n / 10; }
printf("各位数字之和为:%d", sum); return 0;}
Output:
请输入一个数字:654各位数字之和为:15
请输入一个数字:123各位数字之和为:6
热门推荐
-
C语言教程-详解在C语言中的数字反转程序
-
C语言算法-“跳跃游戏”算法问题
-
C++教程-C++语言中的运算符