How to sum the numeric values inside a String in C?

2
For example, if the user types 123456789 the program should print 45 ( 123456789 ). 1 + 2 + 3 + 4 ...) .
I think the easiest way would be to store the number in a string and then add the elements in each position of the string, but I do not know how to add the elements of the string.
Some sites suggest using the atoi() function but it gets the value of the whole string and not a specific element.

    
asked by anonymous 11.09.2017 / 15:50

3 answers

4

The atoi function is for converting an integer string to a number, not each character. To convert a character to number simply use the ASCII table and subtract it.

If you have the character '2' and you want to have the number 2 you can subtract the value of the character '0' that will give you 2

Example:

  • '2' = > letter 50 of the ascii table
  • '0' = > letter 48 of the ascii table

'2'-'0' = 50 - 48 = 2 that was the value you wanted.

To use this in your code you can do the same logic without using the string library and using pointers, like this:

char numero[] = "123456789";

char *letra = numero; //ponteiro letra aponta para o primeiro caractere
int soma = 0;

while (*letra!='
char numero[] = "123456789";

char *letra = numero; //ponteiro letra aponta para o primeiro caractere
int soma = 0;

while (*letra!='%pre%'){ //enquanto não apanhar o terminador da string
    soma += (*letra) - '0'; //conversão de letra para número e soma
    letra++; //aponta para a proxima letra
}

printf("%s dá como soma de numeros %d", numeros,soma);
'){ //enquanto não apanhar o terminador da string soma += (*letra) - '0'; //conversão de letra para número e soma letra++; //aponta para a proxima letra } printf("%s dá como soma de numeros %d", numeros,soma);

See it working on Ideone

    
11.09.2017 / 16:48
1

In C # you can use Convert .ToInt16 :

string digitos = "123456";
string retorno = string.Empty;
int total = 0;
for(int i = 0; i < digitos.Length; i++){
   total += Convert.ToInt16(digitos[i]);

   if (!string.isNullOrEmpty(retorno))
      retorno += " +";
   retorno += digitos[i];
}
retorno = total + " (" + retorno + ")";
Console.WriteLine(retorno);

In C , as I recall, you can do the conversion like this; I believe that printfs set the expected return:

char digitos[6] = "123456";
int total = 0;
for(int i = 0; i < digitos.Length; i++){
   total += (digitos[i] - '0');
}
printf("%s (", total);
for(int i = 0; i < digitos.Length; i++){
   if (i == 0)
      printf("%c ", digitos[i]);
   else
      printf("+ %c", digitos[i]);
}
printf(")",);
    
11.09.2017 / 16:01
0

What about:

#include <stdio.h>

int digsum( const char * s )
{
    int i = 0;
    int soma = 0;

    while( s[i] )
        soma += ( s[i++] - '0' );

    return soma;
}

int main( void )
{
    printf( "%d\n", digsum("123456789") );
    return 0;
}
    
11.09.2017 / 20:21