|
From: Aggro on 23 Nov 2007 15:00 emre esirik(hacettepe com. sci. and eng.) wrote: > I am trying to reserve a word with using recursion algoritim,but it > only puts first capital of the word, why doesnt it puts exactly > word?,can you help me? > > #include <stdio.h> > void reserve(char [], int); > int main(int c,char *argv[]) > { > char word[50]={0}; > int i=0,end_str; > scanf("%s",word); That is very dangerous code. What if someone writes a word which is 100 characters long? Well anything could happen. At least tell scanf to read only 49 characters to avoid bigger problems: scanf("%49s",word); > for(i=0;i<50;i++) > { > if(word[i]=='\0') > { > end_str=i; > break; > } > } > reserve(word,end_str-1); > return 0; > } > void reserve(char word[],int i) > { > if(i!=0) > { > printf("%c", word[i]); > reserve(&word[i-1],i-1); > }else{ > printf("\n"); > } > } Compare these two lines: reserve(word,end_str-1); reserve(&word[i-1],i-1); They are calling the same function, but what difference do they have? You also have one more error left, but you should notice that on your own after fixing the other errors.
From: Ralph D. Ungermann on 27 Nov 2007 12:05 emre esirik(hacettepe com. sci. and eng.) wrote: > I am trying to reserve a word Let's do some magic (others call it `comments'): // print a word backward: // word: the text to print (_not_ necessarily terminated by \0) // The original word remains unchanged (i.e. const) // length: length of the word (ignore word[length] and following) // 0 <= length <= strlen(word) > void reserve(char word[],int i) > { > if(i!=0) > { // 1st: print the last character of the word: > printf("%c", word[i]); // 2nd: reverse the word w/o its last character: > reserve(&word[i-1],i-1); > }else{ // word is empty: > printf("\n"); > } > } First, let us know, whether my assumption of your parameter `i' was right. Rename it to `length', if it is; otherwise rename it to `last_pos', `start_offset', `birthday', or whatever. Second, read the comments, esp. the // 1st... and // 2nd... Correct the statements below them, so that they do what they should. -- Ralph
|
Pages: 1 Prev: I am learning recursion, but I couldnt find my wrong,can u help me? Next: compiler error |