for example, if I typed in 12345 then sum = 1+2+3+4+5 Using C I used some kind of approach that I'm not sure about it and there is a problem with the line referred to down in the code
int i ;
int sum;
int individual;
int n;
printf("enter the number: ");
scanf("%d",&n);
for (i=0;i<5;++i){
**indvidual=+n[i];**
sum=+invidual;
}
printf("%d",sum)
return 0;
You can divide by 10 and see the remainder to obtain each digits.
Also you should use +=
, not =+
, to add things to variable and initialize the variables before using their values.
int i ;
int sum = 0; /* initialize */
int individual;
int n;
printf("enter the number: ");
scanf("%d",&n);
for (i=0;i<5;++i){
indvidual=+(n%10); /* obtain a digit (+ is not required, but left by respect) */
n/=10; /* eliminate last dight and proceed to next digit */
sum+=invidual; /* use += instead of =+ */
}
printf("%d",sum); /* also add semicolon here */
return 0;
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i = 12345;
int sum;
i = abs(i);
sum = i?i%9?i%9:9:0;
printf ("Sum of digits is %d\n", sum);
}
Because 1 + 2 + 3 + 4 + 5 = 15
and then 1 + 5 = 6
(or is the expected output 15
, after just a single pass through the digits?)
#include <stdlib.h> #include <stdio.h> int main() { int i = 12345; int sum=0; i = abs(i); while(i) { sum += i%10; i /= 10; } printf ("Sum of digits is %d\n", sum); return 0; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.