//Program to Calculate the Sum of Digits of a number
clrscr(); // for clearing the console screen
printf("Enter the number : ");
scanf("%d",&num);
temp = num; //copies the value of 'number' in 'temp'
// logic for calculating the sum of digits of number
while(temp != 0) // checking whether 'temp' is equal to 0 or not
{
rem=temp%10; // extracting the last digit by dividing it with 10
#include<stdio.h>
#include<conio.h>
void main()
{
int num, sum=0, temp; /* 'sum' is used to store the sum of digits of a number and 'temp' to store the number for calculations*/
#include<conio.h>
void main()
{
int num, sum=0, temp; /* 'sum' is used to store the sum of digits of a number and 'temp' to store the number for calculations*/
int rem=0; // used to store the remainder of the number
clrscr(); // for clearing the console screen
printf("Enter the number : ");
scanf("%d",&num);
temp = num; //copies the value of 'number' in 'temp'
// logic for calculating the sum of digits of number
while(temp != 0) // checking whether 'temp' is equal to 0 or not
{
rem=temp%10; // extracting the last digit by dividing it with 10
sum=sum+rem; /* calculating the sum of digits of the number - sum is initialized with zero so that no garbage value is added */
temp=temp/10; // dividing the number by 10 to break it in parts.
} // end of while loop
printf("The sum of the digits of a number %d = %d",number,sum); /* printing the sum of digits of number */
printf("The sum of the digits of a number %d = %d",number,sum); /* printing the sum of digits of number */
getch(); // for holding the console screen
}
}
No comments:
Post a Comment