Explanation
The program calculates and prints the sum of the digits of a number entered by the user.
Header
The code begins with including the standard input-output header file using #include <stdio.h>.
Variable Declaration
The main() function is defined, and four integer variables d, m, j, and o are declared. Variable m is initialized to 0 to store the sum of the digits, and o is used to store the original number.
Program Description
The program prints a description message for the user to understand its functionality.
User Input
The user is prompted to enter a number for which they want to calculate the sum of its digits. The input is read using scanf("%d", &d);. The value of d is stored in another variable o for later use.
Sum of Digits Calculation
The program calculates the sum of the digits of the entered number using a while loop:
while (d > 0): Continuously checks ifdis greater than 0.j = d % 10;: Extracts the last digit ofd.m += j;: Adds the extracted digitjto the summ.d /= 10;: Removes the last digit fromd.
Program End
The program prints the sum of the digits stored in m and the original number stored in o. It ends with printf("\n"); to print a new line and return 0; to indicate successful execution.
Code
/*
* -----------------------------------------------------------
* Logic Building with Computer Programming (CSU1128)
* Instructor: Dr. Pankaj Vaidya | Author: Divya Mohan
*
* This code is a part of the educational initiative by dmj.one
* with aim of empowering and inspiring learners in the field of
* Computer Science and Engineering through the respective courses.
*
* (c) 2022, Divya Mohan for dmj.one. All rights reserved.
* -----------------------------------------------------------
*/
#include <stdio.h>
int main()
{
int d, m = 0, j, o;
printf("\n\n Program to print the sum of the digits a user enters. 370 = 3 + 7 + 0 = 10 \n\n");
printf("Enter a number for which you want to calculate the sum of its digits (Example: 211290) - and press enter: ");
scanf("%d", &d);
o = d;
while (d > 0)
{
j = d % 10;
m += j;
d /= 10;
}
printf("\nSum of digits of the entered number %d is %d.", o, m);
printf("\n");
return 0;
}
Output
Program to print the sum of the digits a user enters. 370 = 3 + 7 + 0 = 10
Enter a number for which you want to calculate the sum of its digits (Example: 211290) - and press
enter: 6643
Sum of digits of the entered number 6643 is 19.