Monday, July 9, 2007

How can we sum the digits of a given number in single statement?

Try something like this


# include < stdio.h >

void main()
{
int num=123456;
int sum=0;

for(;num > 0;sum+=num%10,num/=10); // This is the "single line".

printf("\nsum = [%d]\n", sum);
}


If there is a simpler way to do this, let me know!

6 comments:

Deepak said...
This comment has been removed by the author.
Clearer said...

The number of expressions is far more interesting than the number of statments. In the example code you have at least 3 expressions in the one for statment (which you also call 'single line').

you could do something like

do { sum += num % 10} while (num /= 10);

instead, which is better for most compilers, is also a single line, has one less expression in it (doesn't have num > 0) and doesn't reject negative numbers.

Anonymous said...

u r awesome :)doing a great job

sandeep kumar said...

Thanks for the info. It is very helpful.
RegardsEducational site
Get jobs info at Educational site

vikcs said...

nice post Interview Questions

Anonymous said...

void sumdigit(int n) //single line
{
int s = 0;
while((s=s+(n%10))&&(n=n/10)>0)
;
printf("\nSum of Difit : %d",s);
}