• 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
sum of digits in c

correction: here n =number .

# program to find sum of digits of a number in c

  1. #include<stdio.h> // include stdio.h
  2. //c program to find sum of digits of a number using while loop
  3. //write a program to find sum of digits of a number
  4. //www.instanceofjava.com
  5. int main()
  6. {
  7.     // declare variables 
  8.     int number, remainder, sum = 0;
  9.     //read input from user 
  10.     printf("Enter a number: ");
  11.     scanf("%d", &number);

  12.    //iterate until number not equal to zero
  13.    // get individual digits and add all those digits to get sum
  14.     while(number != 0)
  15.     {
  16.         remainder = number % 10;
  17.         sum += remainder;
  18.         number = number / 10;
  19.     }
  20.   //print sum of digits in c
  21.     printf("sum = %d", sum);

  22.     getch();
  23. }


Output:
  1. Enter a number
  2. 123
  3. sum = 6


Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu