Sunday 15 March 2015

c - Recursion using local variable, which is only visible from one "function-part" -



c - Recursion using local variable, which is only visible from one "function-part" -

suppose have next function in c:

#include <stdio.h> int sum(int n); int main(){ int num,add; printf("enter positive integer:\n"); scanf("%d",&num); add=sum(num); printf("sum=%d",add); } int sum(int n){ int temp; temp += 2; printf("temp : %i", temp); if(n==0) homecoming n; else homecoming n+sum(n-1); /*self phone call function sum() */ }

my problem want temp += 2; in first level of loop. want local first loop of sum, , not called sum functions in itself. create question little bit more clear: variable defined in recursive function local first part of recursive "tree"? it's hard explain problem, inquire if don't understand please. thanks!

edit: added printf in sum. output have several times of: temp : 2 temp : 2

but think going happen this:

temp : 2 temp : 4 etc...

edit 2: people seek hard code, here is: (my problem statement ar_in[i]+ space_fill == lw && used[i] == 0 true, want execute there stated after if statement, until return 1; , homecoming way function search_combi. note: ar_in[] array array of several numbers, illustration {10,80,70,60,80})

bool search_combi(int ar_in[], int index){ if (ar_in[index] == lw){ used[index] = 1; comb[combcount][0] = index; homecoming 1; } else{ tempcomb[0] = index; tempcombcount++; space_fill = ar_in[index]; //search right of element search_right(index+1, ar_in); homecoming 0; } } int search_right(int start, int ar_in[]){ int i, j; int temp_space_fill = space_fill; printf("tempspace = %i \n", temp_space_fill); if(choose == 1) { take = 0; homecoming 1; } if(start == cn){ homecoming 1; }else{ for(i = start; < cn; i++){ space_fill = temp_space_fill; if(choose == 1) { break; } if (ar_in[i] + space_fill == lw && used[i] == 0){ tempcomb[tempcombcount] = i; for(j = 0; j <= tempcombcount; j++){ comb[combcount][j] = tempcomb[j]; used[tempcomb[j]] = 1; } combcount++; memset(tempcomb, 0 , sizeof(tempcomb)); tempcombcount = 0; space_fill = 0; temp_space_fill = 0; take = 1; homecoming 1; } else if (ar_in[i] + space_fill < lw && used[i] == 0){ space_fill += ar_in[i]; tempcomb[tempcombcount] = i; tempcombcount++; } search_right(i+1, ar_in); } } homecoming 1; }

local variables located on stack in recursive functions every phone call creates new one, e.g.

void recursion( void ) { int depth = 0; if( depth < 10 ) { depth++; recursion(); } }

will result in endless loop because every recursive phone call creates new depth on stack , initializes 0.

you resolve wrapping actual recursion sth. that:

void recursion( void ) { int depth = 0; recursion_internal( &depth ); } void recursion_internal( int *depth ) { if( *depth < 10 ) { (*depth)++; recursion_internal( depth ); } }

i hope little bit more general illustration helps.

c function variables recursion scope

No comments:

Post a Comment