Add digits of number in C
×


Add digits of number in C

50

 To add the digits of a number in C, you can follow these steps:

 Extract each digit from the number.

 Sum up all the extracted digits.

 Display the result.


 Algorithm to add the digits of a number in C:

 Initialize a variable to store the sum of digits, let's call it sum, and set it to 0.

 Use a loop to extract digits from the number until it becomes 0.

 Inside the loop, extract the rightmost digit of the number using the modulo operator (%) and add it to the sum.

 Remove the rightmost digit from the number using integer division (/).

 Repeat steps 3-4 until the number becomes 0.

 Display the value of sum, which represents the sum of digits.

Example:

// program for adding the digits of a number in C
#include<stdio.h> 

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

    // Input number from the user
    printf("Enter a number: ");
    scanf("%d", &num);

    // Extract digits and add them to the sum
    while (num != 0) {
        digit = num % 10;   // Extract the rightmost digit
        sum += digit;       // Add the digit to the sum
        num /= 10;          // Remove the rightmost digit
    }

    // Display the sum of digits
    printf("Sum of digits: %d\n", sum);

    return 0;
}

Output:

Enter a number: 46
Sum of digits: 10

For example, if the user enters 1234, the program will calculate the sum of digits as 1+2+3+4 = 10 and display it as the output.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments