C Programming
Last Lecture Reminder Functions Named Piece of Code May have a value Return Statement May have input parameters Can function of type int return char value?
Why to Use Functions? Break problem down into smaller sub-tasks Modularity – hides the implementation details We don’t have to keep writing the same thing over and over Make a program much easier to read and maintain
Function Returns Value #include <stdio.h> int max(int x, int y){ if (x<y) return y; else return x; } void main(){ int a,b; printf ("Enter two integers\n"); scanf("%d%d",&a,&b); printf("The maximal number is %d\n",max(a,b));
Void Function void ShowHelp(void) { printf("This function explains what this program does…\n"); printf(“Usage:…"); /* ... */ } int main(void) char choice; printf("Please enter your selection: "); scanf("%c", &choice); if (choice==‘h’) ShowHelp(); else if /* Program continues … */
Pass-by-value Function arguments are passed to the function by copying their values rather than giving the function direct access to the actual variables A change to the value of an argument in a function body will not change the value of variables in the calling function
Pass-by-value - Example int increment(int b) { b=b+1; return b; } int main(void) int a=5,b=1; a = increment(b); printf("a = %d, b = %d\n", a, b); return 0;
Function Declaration #include <stdio.h> int factorial(int a); /* Function Declaration! */ int main(void){ int num; printf("enter a number\n"); scanf("%d", &num); printf("%d != %d\n", num, factorial(num)); return 0; } int factorial(int a){ int i, b = 1; for(i = 1; i <= a; i++) b = b*i; return b;
Scope of Variables Local Variables Global Variables Static Variables Declared in the function Global Variables Declared outside of the function Static Variables
Scope – Local Variables int factorial(int n) { int fact = 1; printf(“fact = %d\n", fact); while (n>1) fact *= n; n--; } return fact; #include <stdio.h> int factorial(int n); int main() { int n, fact = 0; printf("Enter a number\n"); scanf("%d", &n); fact = factorial(n); printf("the factorial is %d\n", fact); printf(“n = %d\n", n); return 0; }
Scope – Global Variables int factorial(int n) { int fact = 1; printf(“GlobalVar = %d\n", ++GlobalVar); while (n>1) fact *= n; n--; } return fact; #include <stdio.h> int GlobalVar = 4; int factorial(int n); int main() { int n, fact = 0; printf(“GlobalVar = %d\n", ++GlobalVar); printf("Enter a number\n"); scanf("%d", &n); fact = factorial(n); printf("the factorial is %d\n", fact); return 0; }
Scope – Static Variables int factorial(int n) { int fact = 1; static int StatVar = 0; printf(“StatVar = %d\n", ++StatVar); while (n>1) fact *= n; n--; } return fact; #include <stdio.h> int factorial(int n); int main() { int n, fact = 0; printf("Enter a number\n"); scanf("%d", &n); for (i = 0; i < 5; i++) { fact = factorial(n); printf("the factorial is %d\n", fact); } return 0;
Recursion
חלוקת השוקולד רוצים לחלק חפיסת שוקולד של 32 קוביות בין 32 תלמידים. רוצים לחלק חפיסת שוקולד של 32 קוביות בין 32 תלמידים. כל חלוקה לוקחת שנייה אחת. השוקולד נמס תוך 6 שניות. כיצד אפשר לבצע את חלוקת החפיסה כך שהשוקולד לא יִמס?
פתרון לשתף את כל הכיתה בחלוקה: המורה תחלק את השוקולד ל-2 ותמסור לשני תלמידים. כל אחד מהתלמידים יחלק את החתיכה שקיבל ל-2 וימסור לשני תלמידים. התהליך יסתיים כאשר כל תלמיד יחזיק קובייה אחת.
Recurrent Algorithm Definition Algorithm that solves the problem by invoking itself on the same simpler\smaller problem until the problem can be solved directly.
Factorial n! = 1*2*3*… *(n-1)*n – General algorithm
Recurrent Problem Definition - Factorial 0! = 1 – Basic case n! = n*(n-1)! – Recurrent step – solving complex case for n>0 – stop condition
Factorial int factorial(int n) { int fact = 1; while (n>1) fact *= n; n--; } return fact; #include <stdio.h> int main() { int n, fact = 0; printf("Enter a number\n"); scanf("%d", &n); fact = factorial(n); printf("the factorial is %d\n", fact); printf(“n = %d\n", n); return 0; }
Recurrent Factorial int recFactorial(int n){ if(n<=1) return 1; return n*recFactorial(n-1); } #include <stdio.h> int main() { int n, fact = 0; printf("Enter a number\n"); scanf("%d", &n); fact = recFactorial(n); printf("the factorial is %d\n", fact); printf(“n = %d\n", n); return 0; }
Recurrent Problem Definition - Factorial 0! = 1 – Basic case n! = n*(n-1)! – Recurrent step – solving complex case for n>0 – Stop condition
Stars Print #include <stdio.h> void star(int n){ while (n<=0){ printf("*"); n--; } void main(){ star(3);
Stars Print #include <stdio.h> void star(int n){ printf("*"); star (n-1); } void main(){ star(3);
Stars Print #include <stdio.h> void star(int n){ if (n<=0) return; printf("*"); star (n-1); } void main(){ star(3);
Types of Recursion Linear Recursion Tail Recursion Binary Recursion רקורסיה "רגילה" Tail Recursion רקורסיית זנב Binary Recursion רקורסיה כפולה Mutual Recursion רקורסיה הדדית
Linear Recursion Call step(n-1) Solve step n Return Result
Solve step (n-1) Call step(n-2) Tail Recursion Solve step n Call step(n-1) Solve step (n-1) Call step(n-2) Solve step 1 Return Result
Binary Recursion Solve step n Call step(n-1) return Solve step 1 return
Mutual Recursion A: Solve step n Call B(n-1) B: Solve step (n-1) Call B(n-2) A: Solve step n-2 Call B(n-3) B: Solve step (n-3) Call B(n-4)
print1 #include <stdio.h> void print1(int n){ if (n==0)return; printf ("%d\n",n); print1(n-1); } void main(){ print1(5);
print2 #include <stdio.h> void print2(int n){ if (n==0)return; print2(n-1); printf ("%d\n",n); } void main(){ print2(5);
Another example - power Xy = x*x*…*x Recursive definitions (assume non-negative y): Base: x0=1 Xy = X*(Xy-1) Xy = (Xy/2)2 (for even y’s only) y times
int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); }
Exercise Write a program that receives two non- negative integers and computes their product recursively. Hint: Notice that the product a*b is actually a+a+…+a (b times).
double power(double val, unsigned pow) { if(pow == 0) / double power(double val, unsigned pow) { if(pow == 0) /* pow(x, 0) returns 1 */ return(1.0); else return(power(val, pow - 1) * val); }