Esc101: Fundamentals of Computing Esc101: Fundamentals of Computing
Esc101: Fundamentals of Computing Esc101: Fundamentals of Computing
Esc101: Fundamentals of Computing Esc101: Fundamentals of Computing
Announcements
Wednesday lab scheduled on 31st August will instead be held y p on Saturday, 3rd September from 2:00 PM to 5:00 PM. Quiz on lab days from 5th to 9th September in Lab at 2:00 PM.
Please ensure that you have moodle access and Computer Center access. If you have forgotten either password, please make sure that you get the problem sorted out before the quiz. No makeup for the quiz.
Lec-16
Lec-16
Recap
Single dimensional arrays as p g y parameters in functions Recursion an introduction
Lec-16
int {
Lec-16
Recursion
Recursion refers to one function calling itself. itself It can also refer to a cyclic function call.
If Function f1() calls Function f2(), Function f2() calls Function f3(), and Function f3() calls Function f1()
Successive recursive calls should be with different parameters, otherwise we can get into an infinite recursion. Th must be a base case, a set of parameters for which There tb b t f t f hi h the answer is returned without further calls. The parameters in successive should be moving towards the base case.
Lec-16 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 5
Example: Factorial
#include <stdio.h> int factorial (int n) { if ((n == 1) || ( == 0)) (( (n // base case: n is 0 or 1 b i return 1; return n * factorial (n-1); // next call is different and } // moves towards base case int main () { int n; scanf (%d, &n); printf (Factorial = %d\n, factorial (n)); }
Lec-16 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 6
Lec-16
Lec-16
Lec-16
Lec-16
10
Lec-16
12
Power function
#include <stdio.h> int power (int x, int n) { int t; if (n == 0) return 1; t = power (x, n/2); if (n%2 != 0) return x * t * t; return t * t; } int main () { i int n, x; scanf (%d %d, &n, &x); printf (power is %d\n, power(x, n)); }
Lec-16 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 13
Any Questions?
Lec-16
14