- To find sum of digits of a number in c , we need to get individual numbers and add those numbers.
- First of all read a number from user using scanf.
- Using while loop get individual number
- Divide the number with 10 so we will get last digit of that number as remainder , once we get that last digit then add it to one variable and divide that number with 10 so it will become one digit less.
- like this we can get all digits and add all those numbers to get sum of digits
- Sum of individual digits in c program
- c program to find sum of digits of a 3 digit number
correction: here n =number .
# program to find sum of digits of a number in c
- #include<stdio.h> // include stdio.h
- //c program to find sum of digits of a number using while loop
- //write a program to find sum of digits of a number
- //www.instanceofjava.com
- int main()
- {
- // declare variables
- int number, remainder, sum = 0;
- //read input from user
- printf("Enter a number: ");
- scanf("%d", &number);
- //iterate until number not equal to zero
- // get individual digits and add all those digits to get sum
- while(number != 0)
- {
- remainder = number % 10;
- sum += remainder;
- number = number / 10;
- }
- //print sum of digits in c
- printf("sum = %d", sum);
- getch();
- }
Output:
- Enter a number
- 123
- sum = 6
No comments