C-Recursion - ECE 175: Introductory C for Engineers...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ECE 175: Introductory C for Engineers Recursion ECE 175: Introductory C for Engineers - Recursion Recursive functions Recursive function: A function that calls itself Characteristics of recursive problems One or more cases of the problem have a straight-forward, non-recursive, solution The other cases can be redefined in terms of problems that are closer to simpler cases Apply this redefinition process every time the recursive function is called Example: Computing factorial of n 2 0 if n < 0 f(n) = 1 if n = 0 n * f(n-1) n > 0 { ECE 175: Introductory C for Engineers - Recursion Parameters and local variable stacks Separate space for parameters and local variables is created upon every call Similar to stack operation Example: Reversing words obtained from input 3 n = 5; word = "one"; n = 4; word = "two"; n = 3; word = "three"; n = 2; word = "four"; n = 1; word = "five"; n = 0; reverse_input_words(int n) { char word[50]; if (n <= 0) return; printf("Enter a word: "); scanf("%s", word); reverse_input_words(n-1); printf("%s ", word); } ECE 175: Introductory C for Engineers - Recursion Reversing a word Example word: ABCDE Note: The words are not copied each time, just the pointers are different 4 w[0] = 'A'; w[0] = 'B'; w[0] = 'C'; w[0] = 'D'; w[0] = 'E'; w[0] = '\0'; reverse_word(char *w) { if (w[0] != '\0') { reverse_word(&w[1]); printf("%c", w[0]); } } A C B D E \0 w w w w w w ECE 175: Introductory C for Engineers - Recursion...
View Full Document

Page1 / 13

C-Recursion - ECE 175: Introductory C for Engineers...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online