# How to write a recursive function?

Posted on

#### Question :

I was given the task of making this function recursive, but I have no idea how to do it.

``````int existe (int x){
FILE *arq;
int y;
char buf[MAX];
arq = fopen ("cliente.txt","r");
fgets (buf,MAX,arq);
while (!feof(arq)){
y = atoi(strtok(buf,";"));
if (x==y){
fclose (arq);
return 1;
}

fgets (buf,MAX,arq);
}
fclose (arq);
return 0;
``````

What is repeated in the function is the cycle `while`

``````    while(!feof(arq)) {
y = atoi(strtok(buf, ";"));
if (x == y) {
fclose(arq);
return 1;
}
fgets(buf, MAX, arq);
}
``````

So it is with slight changes that you need to replace

``````int existe(int x) {
FILE *arq;
arq = fopen("cliente.txt", "r");

int value = existe_rec(x, arq);

fclose(arq);
return value;
}

int existe_rec(int x, FILE *arq) {
char buf[MAX];
if (!fgets(buf, sizeof buf, arq)) return 0;
if (atoi(buf) == x) return 1; // strtok nao é necessário
return existe_rec(x, arq);
}
``````

NB: error validation is missing (which was not present in the original version)!

Instead of offering ready-made source code, which does not help at all if you need to write new recursive functions in the future, I’ll give you tips on how to implement a recursive function .

Any recursive function has the 4 parts below, implemented in this order:

• A decision to continue or stop execution based on a control data, evaluated through a conditional expression. The control data is usually passed to the function as a parameter;
• A body , where the work is done.
• One way to change the control data: : Sometimes changing a counter, or more often by changing which node of the structure is current ;
• A way to reverse the execution flow to go back to the beginning: achieved by invoking the function itself again.
• For example, the following function prints on the screen (recursively) values from `N` to 1 :

``````void countdown(int N)
{
// 1 - Decisão para parar/continuar
if (N < 1)
return;

// 2 - Corpo
printf(“%dn”, N);

// 3 - Alterar o dado de controle
N--;

// 4 - Retrocesso no fluxo de execução
countdown(N);
}
``````