How to add numerical values inside a C string?

Asked

Viewed 6,300 times

2

Good morning, I need to write a code that receives a number and returns the sum of the digits of that number.
For example, if the user type 123456789 the program must print 45 (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 don’t know how to add the elements of the string.
Some websites suggest using the function atoi() but it takes the value of the whole string and not of a specific element.

3 answers

4


The function atoi to convert an entire string to number and not each character. To convert a character to number just use the ascii table and subtract.

If you have the character '2' and want to keep the number 2 can subtract the value of the character '0' you’re gonna give him 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 logic even without using the string library and using pointers, thus:

char numero[] = "123456789";

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

while (*letra!='\0'){ //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);

Watch it work on Ideone

1

In C# you can use the 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 make the conversion that way; I believe printfs mount 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(")",);
  • 1

    In C vectors has no properties. So the digitos.Length should be replaced directly by 6. Or, in this case, there is the option to use the operator sizeof to derive the size of the vector (but only because the statement is in the block itself of the size calculation; if it had in a parameter passage, I do not guarantee that the sizeof work properly)

  • 1

    Another thing, on the first printf: printf("%d (", total);. With the %s the printf will interpret the argument as a pointer to char null terminated, which is possibly not the desired

0

How 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;
}
  • 1

    I did not understand the negative point. Who negatively could explain?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.