C program for Sum of digits of a Number

The below code will calculate the sum of digits of an integer number.

Logic: An integer number like 54321 can be separated into digits by dividing it by 10.If 54321 is divided by 10 then we get remainder 1,and number becomes 5432,if we repeat this process we will get the digits 1 2 3 4 5.

Code:

#include <stdio.h>

#include <conio.h>

void main()

{
    int x,sum;
    sum=0;

    printf("Welcome\nEnter a number:");

    scanf("%d",&x);  //input number

    while(x!=0)

    {
       sum=sum+(x%10);  //get the last digit and add it to sum
       x=x/10;                    //drop the last digit from the number
    }

    printf("\nThe sum is %d",sum);


    printf("\npress any key to continue");

    getch();                       //to halt the execution of the program
}

Post a Comment

CodeNirvana
Newer Posts Older Posts
© Copyright Encyclopedia of C | Designed By Code Nirvana
Back To Top