Program was, WAP to find the sum of the digits of a given number. Here i wasn't knowing about how to calculate the sum of the digits of a number whose size is not give. Finally i reached at the solution and finished this program.
So here it goes..
/*WAP to find the sum of the digits of a given number.*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
long int n,div;
int i,temp,sum=0,length;
char *str;
clrscr();
printf("\nEnter value = ");
scanf("%ld",&n);
ltoa(n,str,10); //converts long int to string
length=strlen(str); //found the length of string
temp=length-1;
div=pow(10,temp);
for(i=0;i<length;i++)>
{
sum+=(n/div)%10;
div=div/10;
}
printf("\n%d",sum);
getch();
}
Alternate Way
void main()
{
long int n,div,temp;
int sum=0;
clrscr();
printf("\nEnter value = ");
scanf("%ld",&n);
while(n>0)
{
temp=n%10;
n=n/10;
sum+=temp;
}
printf("\n%d",sum);
getch();
}
I wish, try this program and if something is wrong in this program then just let me know. If any other idea to make this kind of program even better then also leave a reply with your own idea.
Regards
Amandeep Singh