C Language - add products’ digits (i.e., not the products themselves)2019 Community Moderator ElectionGetting each individual digit from a whole integerImprove INSERT-per-second performance of SQLite?Is 'switch' faster than 'if'?How do I achieve the theoretical maximum of 4 FLOPs per cycle?execution time in C languageCan code that is valid in both C and C++ produce different behavior when compiled in each language?What is the fastest way to calculate e to 2 trillion digits?2 digit sums and all combinations for each sumFind the sum of digits of a number(in c)Limiting my float to only 3 DIGITSinteger overflow in expression, when multiplying 13 digits
What are some noteworthy "mic-drop" moments in math?
Are there historical instances of the capital of a colonising country being temporarily or permanently shifted to one of its colonies?
2×2×2 rubik's cube corner is twisted!
The bar has been raised
Why does Captain Marvel assume the planet where she lands would recognize her credentials?
How are such low op-amp input currents possible?
Why does the negative sign arise in this thermodynamic relation?
Good allowance savings plan?
Replacing Windows 7 security updates with anti-virus?
Algorithm to convert a fixed-length string to the smallest possible collision-free representation?
Is there an equal sign with wider gap?
How strictly should I take "Candidates must be local"?
A question on the ultrafilter number
Do I really need to have a scientific explanation for my premise?
Built-In Shelves/Bookcases - IKEA vs Built
What to do when during a meeting client people start to fight (even physically) with each others?
Can't find the Shader/UVs tab
Virginia employer terminated employee and wants signing bonus returned
How much attack damage does the AC boost from a shield prevent on average?
"One can do his homework in the library"
How did Alan Turing break the enigma code using the hint given by the lady in the bar?
Solving "Resistance between two nodes on a grid" problem in Mathematica
Why don't MCU characters ever seem to have language issues?
Can you reject a postdoc offer after the PI has paid a large sum for flights/accommodation for your visit?
C Language - add products’ digits (i.e., not the products themselves)
2019 Community Moderator ElectionGetting each individual digit from a whole integerImprove INSERT-per-second performance of SQLite?Is 'switch' faster than 'if'?How do I achieve the theoretical maximum of 4 FLOPs per cycle?execution time in C languageCan code that is valid in both C and C++ produce different behavior when compiled in each language?What is the fastest way to calculate e to 2 trillion digits?2 digit sums and all combinations for each sumFind the sum of digits of a number(in c)Limiting my float to only 3 DIGITSinteger overflow in expression, when multiplying 13 digits
I am looking to calculate the below sum but using the products digits, not the products themselves:
These are the initial values:
2 + 12 + 8 = 22
but what I want to achieve is the following, so that the digit 12 is actually seen as a 1 and a 2 separately
2 + 1 + 2 + 8 = 13
Using C language is there a formula in which I can use to perform this task?
c
add a comment |
I am looking to calculate the below sum but using the products digits, not the products themselves:
These are the initial values:
2 + 12 + 8 = 22
but what I want to achieve is the following, so that the digit 12 is actually seen as a 1 and a 2 separately
2 + 1 + 2 + 8 = 13
Using C language is there a formula in which I can use to perform this task?
c
2
No, there is no standard C functions for doing that. However, it's easy to write some code doing that. In a loop you usedigit = n % 10
to get a digit andn = n / 10
to prepare for getting the next digit.
– 4386427
Mar 7 at 8:03
1
where the values come from ? do you have them in an array for instance ? or do you have their external representation (string rather than int) ?
– bruno
Mar 7 at 8:04
See stackoverflow.com/questions/3118490/…
– 4386427
Mar 7 at 8:06
Do you ever have any other operator between the numbers other than+
?
– Bathsheba
Mar 7 at 8:10
add a comment |
I am looking to calculate the below sum but using the products digits, not the products themselves:
These are the initial values:
2 + 12 + 8 = 22
but what I want to achieve is the following, so that the digit 12 is actually seen as a 1 and a 2 separately
2 + 1 + 2 + 8 = 13
Using C language is there a formula in which I can use to perform this task?
c
I am looking to calculate the below sum but using the products digits, not the products themselves:
These are the initial values:
2 + 12 + 8 = 22
but what I want to achieve is the following, so that the digit 12 is actually seen as a 1 and a 2 separately
2 + 1 + 2 + 8 = 13
Using C language is there a formula in which I can use to perform this task?
c
c
asked Mar 7 at 8:00
CoderCoder
9911
9911
2
No, there is no standard C functions for doing that. However, it's easy to write some code doing that. In a loop you usedigit = n % 10
to get a digit andn = n / 10
to prepare for getting the next digit.
– 4386427
Mar 7 at 8:03
1
where the values come from ? do you have them in an array for instance ? or do you have their external representation (string rather than int) ?
– bruno
Mar 7 at 8:04
See stackoverflow.com/questions/3118490/…
– 4386427
Mar 7 at 8:06
Do you ever have any other operator between the numbers other than+
?
– Bathsheba
Mar 7 at 8:10
add a comment |
2
No, there is no standard C functions for doing that. However, it's easy to write some code doing that. In a loop you usedigit = n % 10
to get a digit andn = n / 10
to prepare for getting the next digit.
– 4386427
Mar 7 at 8:03
1
where the values come from ? do you have them in an array for instance ? or do you have their external representation (string rather than int) ?
– bruno
Mar 7 at 8:04
See stackoverflow.com/questions/3118490/…
– 4386427
Mar 7 at 8:06
Do you ever have any other operator between the numbers other than+
?
– Bathsheba
Mar 7 at 8:10
2
2
No, there is no standard C functions for doing that. However, it's easy to write some code doing that. In a loop you use
digit = n % 10
to get a digit and n = n / 10
to prepare for getting the next digit.– 4386427
Mar 7 at 8:03
No, there is no standard C functions for doing that. However, it's easy to write some code doing that. In a loop you use
digit = n % 10
to get a digit and n = n / 10
to prepare for getting the next digit.– 4386427
Mar 7 at 8:03
1
1
where the values come from ? do you have them in an array for instance ? or do you have their external representation (string rather than int) ?
– bruno
Mar 7 at 8:04
where the values come from ? do you have them in an array for instance ? or do you have their external representation (string rather than int) ?
– bruno
Mar 7 at 8:04
See stackoverflow.com/questions/3118490/…
– 4386427
Mar 7 at 8:06
See stackoverflow.com/questions/3118490/…
– 4386427
Mar 7 at 8:06
Do you ever have any other operator between the numbers other than
+
?– Bathsheba
Mar 7 at 8:10
Do you ever have any other operator between the numbers other than
+
?– Bathsheba
Mar 7 at 8:10
add a comment |
3 Answers
3
active
oldest
votes
Supposing you have an array of the values you can do :
#include <stdio.h>
unsigned sum(const unsigned * a, size_t sz)
unsigned sum = 0;
while (sz--)
unsigned v = *a++;
while (v)
sum += v%10;
v /= 10;
return sum;
int main()
const unsigned a[] = 2, 12, 8 ;
printf("sum = %un", sum(a, sizeof(a)/sizeof(*a)));
Compilation and execution :
/tmp % gcc -pedantic -Wextra s.c
/tmp % ./a.out
sum = 13
add a comment |
If +
is the only other token, then you can disregard it and merely sum the digits on the stream. So
#include <stdio.h>
#include <ctype.h> // for isdigit
int main(void)
char* s = "2 + 12 + 8";
int total = 0;
for (; *s; ++s)
if (isdigit((unsigned char)*s))
total += *s - '0';
printf("%dn", total);
is one way. *s - '0';
is the idiomatic way of transforming a char
digit to its numerical value. The loop termination condition is the NUL terminator in the string s
.
This is most certainly not the best approach if you want other operators between terms. At that point you need to build a full expression parser (such as one based on the worked example in Kernighan & Ritchie).
1
To avoid undefined behavior on negativechar
values on systems that have signedchar
by default, you should writeisdigit((unsigned char)*s)
. I might be more readable to write(*s >= '0' && *s <= '9')
– chqrlie
Mar 7 at 8:22
@chqrlie: I can still here my professor shouting at me for this all those years ago. Fixed.
– Bathsheba
Mar 7 at 8:23
add a comment |
There is no direct formula for this task but you can perform this task in a separate function and use that function wherever it is needed.
Here are two simple solutions which depend on the type of input.
If Input is in the form of String (i.e. "2 + 12 + 8") then the code will be -
#include <stdio.h>
int main()
char str[] = "2 + 12 + 8";
int sum=0;
for (int i = 0; i < strlen(str); i++)
if (str[i] >= '0' && str[i] <= '9')
sum += str[i] - '0';
printf("%d",sum);
return 0;
If Input is in the form of Array (i.e. [2, 12, 8]) then the code will be -
#include <stdio.h>
int main()
int num[] = 2, 12, 8;
int sum=0;
int length = sizeof(num) / sizeof(num[0]);
for (int i = 0; i < length; i++)
while (num[i])
sum += num[i] % 10;
num[i] /= 10;
printf("%d",sum);
return 0;
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55038757%2fc-language-add-products-digits-i-e-not-the-products-themselves%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Supposing you have an array of the values you can do :
#include <stdio.h>
unsigned sum(const unsigned * a, size_t sz)
unsigned sum = 0;
while (sz--)
unsigned v = *a++;
while (v)
sum += v%10;
v /= 10;
return sum;
int main()
const unsigned a[] = 2, 12, 8 ;
printf("sum = %un", sum(a, sizeof(a)/sizeof(*a)));
Compilation and execution :
/tmp % gcc -pedantic -Wextra s.c
/tmp % ./a.out
sum = 13
add a comment |
Supposing you have an array of the values you can do :
#include <stdio.h>
unsigned sum(const unsigned * a, size_t sz)
unsigned sum = 0;
while (sz--)
unsigned v = *a++;
while (v)
sum += v%10;
v /= 10;
return sum;
int main()
const unsigned a[] = 2, 12, 8 ;
printf("sum = %un", sum(a, sizeof(a)/sizeof(*a)));
Compilation and execution :
/tmp % gcc -pedantic -Wextra s.c
/tmp % ./a.out
sum = 13
add a comment |
Supposing you have an array of the values you can do :
#include <stdio.h>
unsigned sum(const unsigned * a, size_t sz)
unsigned sum = 0;
while (sz--)
unsigned v = *a++;
while (v)
sum += v%10;
v /= 10;
return sum;
int main()
const unsigned a[] = 2, 12, 8 ;
printf("sum = %un", sum(a, sizeof(a)/sizeof(*a)));
Compilation and execution :
/tmp % gcc -pedantic -Wextra s.c
/tmp % ./a.out
sum = 13
Supposing you have an array of the values you can do :
#include <stdio.h>
unsigned sum(const unsigned * a, size_t sz)
unsigned sum = 0;
while (sz--)
unsigned v = *a++;
while (v)
sum += v%10;
v /= 10;
return sum;
int main()
const unsigned a[] = 2, 12, 8 ;
printf("sum = %un", sum(a, sizeof(a)/sizeof(*a)));
Compilation and execution :
/tmp % gcc -pedantic -Wextra s.c
/tmp % ./a.out
sum = 13
answered Mar 7 at 8:11
brunobruno
10.2k21126
10.2k21126
add a comment |
add a comment |
If +
is the only other token, then you can disregard it and merely sum the digits on the stream. So
#include <stdio.h>
#include <ctype.h> // for isdigit
int main(void)
char* s = "2 + 12 + 8";
int total = 0;
for (; *s; ++s)
if (isdigit((unsigned char)*s))
total += *s - '0';
printf("%dn", total);
is one way. *s - '0';
is the idiomatic way of transforming a char
digit to its numerical value. The loop termination condition is the NUL terminator in the string s
.
This is most certainly not the best approach if you want other operators between terms. At that point you need to build a full expression parser (such as one based on the worked example in Kernighan & Ritchie).
1
To avoid undefined behavior on negativechar
values on systems that have signedchar
by default, you should writeisdigit((unsigned char)*s)
. I might be more readable to write(*s >= '0' && *s <= '9')
– chqrlie
Mar 7 at 8:22
@chqrlie: I can still here my professor shouting at me for this all those years ago. Fixed.
– Bathsheba
Mar 7 at 8:23
add a comment |
If +
is the only other token, then you can disregard it and merely sum the digits on the stream. So
#include <stdio.h>
#include <ctype.h> // for isdigit
int main(void)
char* s = "2 + 12 + 8";
int total = 0;
for (; *s; ++s)
if (isdigit((unsigned char)*s))
total += *s - '0';
printf("%dn", total);
is one way. *s - '0';
is the idiomatic way of transforming a char
digit to its numerical value. The loop termination condition is the NUL terminator in the string s
.
This is most certainly not the best approach if you want other operators between terms. At that point you need to build a full expression parser (such as one based on the worked example in Kernighan & Ritchie).
1
To avoid undefined behavior on negativechar
values on systems that have signedchar
by default, you should writeisdigit((unsigned char)*s)
. I might be more readable to write(*s >= '0' && *s <= '9')
– chqrlie
Mar 7 at 8:22
@chqrlie: I can still here my professor shouting at me for this all those years ago. Fixed.
– Bathsheba
Mar 7 at 8:23
add a comment |
If +
is the only other token, then you can disregard it and merely sum the digits on the stream. So
#include <stdio.h>
#include <ctype.h> // for isdigit
int main(void)
char* s = "2 + 12 + 8";
int total = 0;
for (; *s; ++s)
if (isdigit((unsigned char)*s))
total += *s - '0';
printf("%dn", total);
is one way. *s - '0';
is the idiomatic way of transforming a char
digit to its numerical value. The loop termination condition is the NUL terminator in the string s
.
This is most certainly not the best approach if you want other operators between terms. At that point you need to build a full expression parser (such as one based on the worked example in Kernighan & Ritchie).
If +
is the only other token, then you can disregard it and merely sum the digits on the stream. So
#include <stdio.h>
#include <ctype.h> // for isdigit
int main(void)
char* s = "2 + 12 + 8";
int total = 0;
for (; *s; ++s)
if (isdigit((unsigned char)*s))
total += *s - '0';
printf("%dn", total);
is one way. *s - '0';
is the idiomatic way of transforming a char
digit to its numerical value. The loop termination condition is the NUL terminator in the string s
.
This is most certainly not the best approach if you want other operators between terms. At that point you need to build a full expression parser (such as one based on the worked example in Kernighan & Ritchie).
edited Mar 7 at 8:30
answered Mar 7 at 8:13
BathshebaBathsheba
180k27254383
180k27254383
1
To avoid undefined behavior on negativechar
values on systems that have signedchar
by default, you should writeisdigit((unsigned char)*s)
. I might be more readable to write(*s >= '0' && *s <= '9')
– chqrlie
Mar 7 at 8:22
@chqrlie: I can still here my professor shouting at me for this all those years ago. Fixed.
– Bathsheba
Mar 7 at 8:23
add a comment |
1
To avoid undefined behavior on negativechar
values on systems that have signedchar
by default, you should writeisdigit((unsigned char)*s)
. I might be more readable to write(*s >= '0' && *s <= '9')
– chqrlie
Mar 7 at 8:22
@chqrlie: I can still here my professor shouting at me for this all those years ago. Fixed.
– Bathsheba
Mar 7 at 8:23
1
1
To avoid undefined behavior on negative
char
values on systems that have signed char
by default, you should write isdigit((unsigned char)*s)
. I might be more readable to write (*s >= '0' && *s <= '9')
– chqrlie
Mar 7 at 8:22
To avoid undefined behavior on negative
char
values on systems that have signed char
by default, you should write isdigit((unsigned char)*s)
. I might be more readable to write (*s >= '0' && *s <= '9')
– chqrlie
Mar 7 at 8:22
@chqrlie: I can still here my professor shouting at me for this all those years ago. Fixed.
– Bathsheba
Mar 7 at 8:23
@chqrlie: I can still here my professor shouting at me for this all those years ago. Fixed.
– Bathsheba
Mar 7 at 8:23
add a comment |
There is no direct formula for this task but you can perform this task in a separate function and use that function wherever it is needed.
Here are two simple solutions which depend on the type of input.
If Input is in the form of String (i.e. "2 + 12 + 8") then the code will be -
#include <stdio.h>
int main()
char str[] = "2 + 12 + 8";
int sum=0;
for (int i = 0; i < strlen(str); i++)
if (str[i] >= '0' && str[i] <= '9')
sum += str[i] - '0';
printf("%d",sum);
return 0;
If Input is in the form of Array (i.e. [2, 12, 8]) then the code will be -
#include <stdio.h>
int main()
int num[] = 2, 12, 8;
int sum=0;
int length = sizeof(num) / sizeof(num[0]);
for (int i = 0; i < length; i++)
while (num[i])
sum += num[i] % 10;
num[i] /= 10;
printf("%d",sum);
return 0;
add a comment |
There is no direct formula for this task but you can perform this task in a separate function and use that function wherever it is needed.
Here are two simple solutions which depend on the type of input.
If Input is in the form of String (i.e. "2 + 12 + 8") then the code will be -
#include <stdio.h>
int main()
char str[] = "2 + 12 + 8";
int sum=0;
for (int i = 0; i < strlen(str); i++)
if (str[i] >= '0' && str[i] <= '9')
sum += str[i] - '0';
printf("%d",sum);
return 0;
If Input is in the form of Array (i.e. [2, 12, 8]) then the code will be -
#include <stdio.h>
int main()
int num[] = 2, 12, 8;
int sum=0;
int length = sizeof(num) / sizeof(num[0]);
for (int i = 0; i < length; i++)
while (num[i])
sum += num[i] % 10;
num[i] /= 10;
printf("%d",sum);
return 0;
add a comment |
There is no direct formula for this task but you can perform this task in a separate function and use that function wherever it is needed.
Here are two simple solutions which depend on the type of input.
If Input is in the form of String (i.e. "2 + 12 + 8") then the code will be -
#include <stdio.h>
int main()
char str[] = "2 + 12 + 8";
int sum=0;
for (int i = 0; i < strlen(str); i++)
if (str[i] >= '0' && str[i] <= '9')
sum += str[i] - '0';
printf("%d",sum);
return 0;
If Input is in the form of Array (i.e. [2, 12, 8]) then the code will be -
#include <stdio.h>
int main()
int num[] = 2, 12, 8;
int sum=0;
int length = sizeof(num) / sizeof(num[0]);
for (int i = 0; i < length; i++)
while (num[i])
sum += num[i] % 10;
num[i] /= 10;
printf("%d",sum);
return 0;
There is no direct formula for this task but you can perform this task in a separate function and use that function wherever it is needed.
Here are two simple solutions which depend on the type of input.
If Input is in the form of String (i.e. "2 + 12 + 8") then the code will be -
#include <stdio.h>
int main()
char str[] = "2 + 12 + 8";
int sum=0;
for (int i = 0; i < strlen(str); i++)
if (str[i] >= '0' && str[i] <= '9')
sum += str[i] - '0';
printf("%d",sum);
return 0;
If Input is in the form of Array (i.e. [2, 12, 8]) then the code will be -
#include <stdio.h>
int main()
int num[] = 2, 12, 8;
int sum=0;
int length = sizeof(num) / sizeof(num[0]);
for (int i = 0; i < length; i++)
while (num[i])
sum += num[i] % 10;
num[i] /= 10;
printf("%d",sum);
return 0;
answered Mar 7 at 11:59
Arpit SethArpit Seth
192
192
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55038757%2fc-language-add-products-digits-i-e-not-the-products-themselves%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
No, there is no standard C functions for doing that. However, it's easy to write some code doing that. In a loop you use
digit = n % 10
to get a digit andn = n / 10
to prepare for getting the next digit.– 4386427
Mar 7 at 8:03
1
where the values come from ? do you have them in an array for instance ? or do you have their external representation (string rather than int) ?
– bruno
Mar 7 at 8:04
See stackoverflow.com/questions/3118490/…
– 4386427
Mar 7 at 8:06
Do you ever have any other operator between the numbers other than
+
?– Bathsheba
Mar 7 at 8:10