FYBCom(CA) C Practical Slip 5 Q 1.B

C Program to Calculate Sum of Digits of a Number

1. Introduction

Calculating the sum of digits is a common beginner-level C programming problem. It helps students understand loops, arithmetic operations, and number manipulation.

2. Problem Statement

Question: Write a C program to calculate the sum of digits of a number.
Example: If the number is 987, the sum is 9 + 8 + 7 = 24.

3. Logic

To calculate the sum of digits:

  1. Accept an integer number from the user.
  2. Extract the last digit using the modulus operator (% 10).
  3. Add the digit to a sum variable.
  4. Remove the last digit using division (/ 10).
  5. Repeat the process until the number becomes 0.
  6. Display the final sum.

4. Source Code

Here is a beginner-friendly C program:

#include <stdio.h>

int main() {
    int number, sum = 0, digit;

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

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

    printf("Sum of digits = %d\n", sum);

    return 0;
}

5. Sample Output

Enter a number: 987
Sum of digits = 24
Enter a number: 1234
Sum of digits = 10

6. Viva Questions

  1. Q: Which operator is used to extract the last digit of a number?
    A: The modulus operator %.
  2. Q: Why do we divide the number by 10 in each iteration?
    A: To remove the last digit from the number.
  3. Q: Which loop is used in this program?
    A: while loop.
  4. Q: Can this program work for negative numbers?
    A: It can, but typically we convert the number to positive using abs().
  5. Q: What is the time complexity of this program?
    A: O(n), where n is the number of digits in the number.
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top