ADVERTISEMENT
Sum of All Digits in a Number
This code takes a positive integer input, extracts each digit, calculates the sum of these digits, and then displays the original number and the sum. The program utilizes a while loop to achieve this task.
#include<stdio.h>
main()
{
int dummy,n,sum=0,x;
printf("Enter a number\n");
scanf("%d",&n);
dummy=n;
while(n>0)
{
x=n%10;
sum=sum+x;
n=n/10;
}
printf("The sum of all digits in %d is %d\n",dummy,sum);
}C Programming ExamplesExplanation:
This C program calculates the sum of all the digits in a positive integer entered by the user. Here’s a step-by-step explanation of the code:
Header File:
The program includes the standard C library header <stdio.h> for input and output operations.
Main Function:
The main function is the entry point of the program.
Variable Declaration:
Four variables are declared:
- n (int): It is used to store the user input, which is the number for which the digit sum is to be calculated.
- dummy (int): This variable stores a copy of n for later printing the result.
- sum (int): This variable is used to accumulate the sum of digits.
- x (int): It temporarily stores each digit extracted from n.
User Input:
The program prompts the user to enter a number:
- “Enter a number” for n.
The user’s input is read and stored in the variable n using scanf.
Initialization:
dummy is set to the same value as n. This step is done to keep a copy of the original number, as n will be modified in the subsequent calculations.
While Loop:
- The code uses a while loop to extract and sum the individual digits of the number n.
- The loop continues as long as n is greater than 0.
Digit Extraction:
- Within the loop, x is used to store the rightmost digit of n. This is done by calculating n % 10, which gives the remainder when n is divided by 10. This remainder is the rightmost digit.
Sum Calculation:
- The value of x (the rightmost digit) is added to the sum. This step accumulates the sum of the digits.
Digit Removal:
- The rightmost digit is removed from n by dividing it by 10 (n = n / 10). This operation effectively removes the rightmost digit, and the process continues with the remaining digits.
Print Result:
- After the loop completes, the program uses printf() to display the original number and the sum of its digits. The format specifier %d is used to print integer values.
End of Program:
- Once the result is displayed, the program reaches the end of the main function and terminates.