Write a program to adding a digits from given number in c
Adding a digits from given number in c
To write a program to add the digits of a given number in C, we can use the following steps:
- Declare a variable to store the number that we want to add the digits of.
- Declare another variable to store the sum of the digits.
- Initialize the sum of the digits to 0.
- While the number is greater than 0, do the following:
- Get the rightmost digit of the number.
- Add the rightmost digit to the sum of the digits.
- Divide the number by 10 to remove the rightmost digit.
- Print the sum of the digits to the console.
Here is a simple C program to add the digits of a given number:
C Programming
#include <stdio.h>
int main() {
int number, sum_of_digits;
printf("Enter a number: ");
scanf("%d", &number);
sum_of_digits = 0;
while (number > 0) {
int rightmost_digit = number % 10;
sum_of_digits += rightmost_digit;
number /= 10;
}
printf("The sum of the digits of %d is %d\n", number, sum_of_digits);
return 0;
}
Output:
Enter a number: 1234
The sum of the digits of 1234 is 10
This program is simple, but it is effective. It uses a while loop to iterate over the digits of the number and add them to the sum of the digits. Once the loop has finished iterating, the sum of the digits is printed to the console.
Further Reading:
Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!