cs-laz cs-laz - 3 months ago 14
C Question

How to sum all values in a same variable?

I am working on an assignment but the code is doing some weird stuff. It is my 7th day "programming", so it might be just an obvious mistake, which I simply cannot see.

I want the program to sum all values stored in a same variable. I tried to replicate some code from here: https://stackoverflow.com/a/42166389, but it did not work as expected.

So, given a set of values -let's say 012345-, the program should take every other number -4, 2, and 0-, and sum them -giving back "6"-. And, although it does identify the digits, it does not sum them... at least properly.
I do not understand why, but it gives back 48.

I have tried different inputs, and while identifying the digits properly, in all cases the sum was wrong.

I would really appreciate any help.
Oh, and here is my code!:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void) {
char c;
string number;
int length, i, sum = 0;

printf("Type card number: ");
number = get_string();

printf("Tell us how many characters long was your number: ");
length = get_int();

for (i = 1; i <= length / 2; i++) {
c = number[(strlen(number) - i * 2)];
sum = c;
printf("%c %i %s\n", c, sum, number);
}
}


Some examples:

For input
012345
and
length=6
, the output is:

4 52 012345
2 50 012345
0 48 012345


For input
9876543210
and
length=10
, the output is:

1 49 9876543210
3 51 9876543210
5 53 9876543210
7 55 9876543210
9 57 9876543210


And, just to summarize, what I want is a way of summing all the values in a same variable.

Answer Source
 sum = c;

You are assigning ASCII value to sum.You should get the corresponding number and also add it to sum, not just assign.

 4 52 012345  //52 is ASCII value of 4
 2 50 012345  //50 is ASCII value of 2
 0 48 012345  //48 is ASCII value of 0

Try this,

 sum+=c-'0';