Doubt about recursiveness in C

Asked

Viewed 624 times

1

I’m learning about recursion, using the C language, and I have to do the following exercise:

Design a recursive function that takes an integer n and compute the sum of the digits of n.

For example:

for n = 327, the result is 12 = 3 + 2 + 7.

I even have a solution to this problem, which would be the following code:

 int soma(int n){
 if(n%10 == n)
 return n;
 else
 return ((n % 10) + soma(n/10));
 }
 

But I don’t exactly understand the logic of this code, so I’d appreciate it if you could explain to me =]

  • Have you tried the table test?

  • You can study a lot about recursion here: https://answall.com/a/267825/64969

  • Yeah, but I still don’t get it. For example, in if (327%10 == 327) I would have 7 == 327, which is not true, and so I go to Else, which returns me (327%10 [which is 7])) + sum (327/10) [which is 32.7). From that moment on I do not understand exactly what happens, because from what I understood I will have 39 (that would be 7+32,7, but without the decimal) and this should not be right, but I also do not know the right way

  • I think I understand your doubt. In this case, in C and in almost every language I know (except for [tag:python-3], when dividing an integer by another one you get a new integer. So 327/10 ==> 32, nay 32,7 as we learn in the arithmetic of rational numbers. Welcome to the world of programming, where you must know at least 4 distinct arithmetic to really know what you are doing: integer arithmetic, fixed-point arithmetic, floating-point arithmetic and arbitrary precision arithmetic.

3 answers

5


Changing only the call order, but keeping the same direction:

 return (soma(n/10) + (n % 10));

Each time you will call the same function again, you are passing the number without the first digit on the right, what happens when you perform the n/10 (note that the division only returns to entire part of the division). This process is repeated until n%10 == n (which in this case occurs in the 3° Call). When the termination condition is found in the third call (i.e. n == 3 and n%10 == 3, then n%10 == n), the function starts to return the rest of the division, ie the first digit on the right n%10, added with the rest of the function in which you called it. with that you are adding all the remnants of the division, or, all the digits of the number.

inserir a descrição da imagem aqui

If we were to expand into a recursive notation, we would have:

soma(327)
soma(32) + 7
soma(3) + 2 + 7
3 + 2 + 7

Or in binary tree notation

inserir a descrição da imagem aqui

2

Code:

#include <iostream>

int soma(int n){

 if(n%10 == n)
    return n;
 else
    return ((n % 10) + soma(n/10));

}

int main(int argc, char** argv) {
    printf("%d\n", soma(327));
    return 0;
}

Upshot:

inserir a descrição da imagem aqui

Explanation:

Step by step function soma() passing as parameter the value 327.

Step 1:

int soma(int n){ // n= 327

 if(n%10 == n) // O resto da divisão de 327 por 10 é igual a 327? não, então vamos para o else..
    return n;
 else
    return ((n % 10) + soma(n/10)); 
    // Retorna o resto da divisão de 327 por 10 mais o retorno da função 
    // soma passando como parâmetro o resultado inteiro da divisão de 327 
    // por 10, ou seja, retorna 7 mais o retorno de soma(32).
}

Step 2:

int soma(int n){ // n= 32

 if(n%10 == n) // O resto da divisão de 32 por 10 é igual a 32? não, então vamos para o else..
    return n;
 else
    return ((n % 10) + soma(n/10)); 
    // Retorna o resto da divisão de 32 por 10 mais o retorno da função 
    // soma passando como parâmetro o resultado inteiro da divisão de 32 
    // por 10, ou seja, retorna 2 mais o retorno de soma(3).
}

Step 3:

int soma(int n){ // n= 3

 if(n%10 == n) // O resto da divisão de 3 por 10 é igual a 3? Sim!!
    return n; //Então retorna 3
 else
    return ((n % 10) + soma(n/10));
}

Step 4:

 //Somar os valores que estam na pilha de memória 3+2+7

Illustration of the recursive method:

inserir a descrição da imagem aqui

-1

From what I understand of your question what you want is the following (and using recursiveness):

#include <stdio.h>

int somarDigitos(int valor)
{
    if (valor == 0)
        return 0;
    else 
        return (valor % 10) + somarDigitos(valor /= 10);
}


int main(void) {

    int soma = somarDigitos(372);
    printf("%d\n", soma);
    return 0;
}

What the function does is always take the last element of the number through the function mod(%), which takes the result of the division by 10, and calls the function again by dividing the value by 10, thus eliminating the last digit, until it reaches the last.

Browser other questions tagged

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