hi
is there any better method for finding sum of three numbers??
Code:#include<stdio.h> main() { int a,s; printf("enter a number"); scanf("%d",&a); for( ;a!=0;) { s=s+(a%10); a=a/10; } printf("the sum is%d",s); getch(); }
hi
is there any better method for finding sum of three numbers??
Code:#include<stdio.h> main() { int a,s; printf("enter a number"); scanf("%d",&a); for( ;a!=0;) { s=s+(a%10); a=a/10; } printf("the sum is%d",s); getch(); }
You mean the sum of the digits? No, not really. Since this code won't work properly with negative numbers, you should make a and s an unsigned int (use %u instead of %d). You should also write "int main()" instead of "main()" since C99 will require explicit return types. You could also write "s += a%10;" and "a /= 10;".
Edit: Better yet, "int main(void)". You could also replace "for( ;a!=0;)" with the clearer "while (a != 0)" or just "while (a)".
Last edited by robatino; 08-16-2007 at 11:03 AM.
Since you are processing the number digit-by-digit anyway, there's no much point in converting it to a real integer at all:
Code:int main() { char number[16], *ptr; int sum = 0; scanf("%15s", number); for(ptr = number; *ptr; ptr++) { sum += *ptr - '0'; } printf("The sum is %d", sum); return 0; }
No, that's not the best way.
Try learning some math, like some "Sum of" algorithms.