c - How this recursive function returns a value to main? -



c - How this recursive function returns a value to main? -

i've spent hours trying figure out why recursive function works when return statement within if (base case).

#include<stdio.h> int main( void ) { int sum_recursive_function( int const number_copy );//function prototype int number, sum_recursive; puts( "please type number , add together digits:" ); scanf( "%d", &number ); sum_recursive = sum_recursive_function( number ); printf( "%s%d\n", "the sum of digits is: ", sum_recursive ); } int sum_recursive_function( int const number_copy ) { int last_digit, sum_pre = 0; if( number_copy == 0 ){ homecoming sum_pre; } else{ last_digit = number_copy % 10; sum_pre = last_digit + sum_recursive_function( number_copy / 10 ); } }

i understand this: if type number 1, if within function checks if number_copy equal 0, not, gets else statment, remainder of 1 divided 10 = 1 assigned last_digit. last_digit (1) added recursive phone call sends 1/10=0 sum_recursive_function. time sum_recursive_function checks if argument equal 0, , equal 0, returns sum_pre 0. sum_pre = 1 + 0. , not understand how sum_recursive_function returns sum_pre (1) main.

your code exhibits undefined behavior. sum_recursive_function() needs homecoming value.

let's prepare it:

int sum_recursive_function(int const number_copy) { if (number_copy == 0) { homecoming 0; } else { int last_digit = number_copy % 10; homecoming last_digit + sum_recursive_function( number_copy / 10 ); } }

perhaps right code allow understand better.

c recursion

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -