4
I’ve been tasked with making this function recursive, but I have no idea how to do that.
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;
It can’t be recursive, it’s possible to use recursion in part of it. But here’s the question, what’s the point? Are you going to get something out of it? Making an unsolicited recursion is not a good reason. The main reason to do this is when it is intended to make an appeal. If you’re having trouble doing it, then you don’t have to. Honestly, in this case, I wouldn’t waste any time trying. It is better to do without being recursive anyway. The algorithm looks sequence and not recursive. Any attempt will make the algorithm look worse.
– Maniero
@Bigown: No need to keep asking the utility... this task is clearly an exercise.
– hugomg
Is this an exercise? What are the requirements? In other words, what exactly does it need to be a recursive task? (reading and processing of a single token?)
– mgibsonbr
Getting back to the point, SOPT works best when your question is very specific. What have you tried so far? Why do you think you can not solve the problem? Without more details the only thing we can do is give the answer ready and this is not funny :)
– hugomg
@hugomg even if it is, it is bad formulated. My answer would be "it is better to leave so than to learn to do wrong thing".
– Maniero
The OP question is missing details but I disagree that it is poorly formulated. Who passed the task simply wants to see if the OP knows how to replace loops with recursion (this is something useful to know, even if the most common is to do this conversion in the opposite direction).
– hugomg
For me the problem here is that I have no idea what this function does. There is nothing descriptive.
– Pablo Almeida
@Pablo.
cliente.txt
is a csv. The function in question reads the first column in each row and sees if it isx
, returning 1 to findx
or 0 otherwise. Probably Josh’s teacher wants him to rewrite the center of that logic with a recursive function with halting casesEOF
andx==y
. Well, my tip got bigger than the amount of code needed to solve this exercise :).– Anthony Accioly
y = atoi(strtok(buf,";"));
does exactly the same thingy = atoi(buf);
only the latter is much more efficient :-)– pmg