40 : C Program to Calculate Sum of digits of entered number

Check out the complete list of c-programs : C Program List    



This C program accepts a integer and calculates the sum of all digits. The logic is similar to the previous example.

Logic :

while(number >=1 ) {
       
      temp_var = number%10; //get unit place digit
      sum = sum + temp_var; //add them to sum variable
      number = number/10; //remove the last digit
       
   }


Variables :

1. number : Datatype int : Holds value of number inputted by the user.

2. temp_var : Datatype int : To hold temporary values.

3. sum : Datatype int : Holds the sum of digits value.



Functions :

printf() : is used to display something on the console/screen. Format specifier %d in printf function is used to display a int variable on screen and %f for float. \n is used to add a newline

scanf() : is used to fetch data inputted by the user on the console/screen using keyboard. %d in scanf is indicates that inputted text is of type int.



Logic :

while(number >=1 ) {

temp_var = number%10; //get unit place digit

sum = sum + temp_var; //add them

number = number/10; //remove the last digit

}








/*
 * 1000+ C programs + tutorials
 *
 * 
 * 40_calculate_sum_of_digits_of_entered_number.c
 *
 *
 *  Created on: Oct 20, 2014
 *  Author: Code2care.org
 */

#include 
//#include 



void main() {

   int number,sum = 0,temp_var;
  

//    clrscr();

    printf("C Program to Calculate sum of Digits of Entered Number");

    printf("\n\n Enter Number : ");
    scanf("%i", &number);
    
    printf("\n\n Entered Number    : %i",number);
     
     
   //Logic to calculate sum
   
   while(number >=1 ) {
       
      temp_var = number%10; //get unit place digit
      sum = sum + temp_var; //add them
      number = number/10; //remove the last digit
       
       
   }
    
   
   printf("\n\n Sum of Digits : %i", sum);
    
 

//	getch();



}









The best way to learn C programming is to practice more and more of programs . Code2care C Programming tutorials provide 1000+ programs in C that you can study and become an expert in the language. Programs are divided into categories depending upon type and complexity.

BSc. IT, BSc. Computer Science, BSc. IT, MSc. IT, MSc. Computer Science, MCA, BTech IT & BTech Engineers may find these programs very useful.