ZBLOG

Function to calculate the sum of digits of a number in c

Here’s a simple C function to calculate the sum of the digits of a number:

#include <stdio.h>

int sumOfDigits(int n) {
    int sum = 0;

    // Make sure to work with positive numbers
    n = (n < 0) ? -n : n; 

    while (n != 0) {
        sum += n % 10; // Add last digit to sum
        n /= 10;       // Remove last digit from n
    }

    return sum;
}

int main() {
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    int result = sumOfDigits(number);
    
    printf("Sum of digits: %d\n", result);
    
    return 0;
}

Explanation:

  1. Function Definition: sumOfDigits takes an integer n as input and returns the sum of its digits.
  2. Handling Negative Numbers: The function converts negative numbers to positive using the ternary operator, so it can handle both cases properly.
  3. While Loop: The loop continues until there are no more digits left in the number (n becomes 0). Inside the loop, it adds the last digit to sum and removes that digit from n.
  4. Main Function: It prompts the user for input, calls the sumOfDigits function, and prints the result.

You can compile this code using any C compiler and run it to see how it works!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=21377

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?