1 / 30

Introduction to Computer Algorithmics and Programming Ceng 113

Introduction to Computer Algorithmics and Programming Ceng 113. Functions and Recursive Functions. Functions. The general form of a function is; type_specifier function_name( parameter list ) { body of the function }

kyran
Download Presentation

Introduction to Computer Algorithmics and Programming Ceng 113

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Computer Algorithmics and ProgrammingCeng 113 Functions and Recursive Functions

  2. Functions • The general form of a function is; type_specifier function_name(parameterlist) { body of the function } • The type_specifier specifies the type of value that the return statement of the function returns. If no type is specified, the compiler assumes that the function returns an integer result.

  3. Functions • type_specifier function_name(type var_name1,..., type var_nameN) • { • body of the function • } • The parameter list is a comma sperated list of variable names and types that receive the values of the arguments when the function called.

  4. Scope Rules of Functions • Each function is discrete block of code (for instance, you cannot use goto to jump into middle of another function). • Variables that are defined within a function are called local variables. Local variables cannot hold their value between function calls. The only exception to this rule is when the variable is declared with static storage class specifier. • You cannot define a function within a function. • If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. They behave like other local variables.

  5. Example • /* return 1 if c is part of string s; 0 otherwise */ • is_in(char *s, char c) • { • while(*s) • if (*s==c) return 1; • else s++; • return 0; • }

  6. call by value / call by reference • Subroutines can be passed arguments in one of two ways; • Call by value; This method copies the value of an argument into the formal parameter of the subroutine. • Call by reference; In this method, the address is used to access the actual argument used in the call. #include <stdio.h> void swap(int *a, int *b); void main(void) { int x, y; x=10; y = 20; swap(&x, &y); } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } #include <stdio.h> int sqr(int x); void main(void) { int t=10; printf(“%d %d”, sqr(t), t); } sqr(int x) { x= x*x; return x; }

  7. Calling Functions with Arrays • In C, an array name without any index is a pointer to the first element in the array. • There are three ways to declare a parameter to receive an array pointer: 2. It may be declare as an unsized array; #include <stdio.h> void main(void) { int t[10], i; for(i=0; i<10; ++i) t[i]=i; display(t); } void display(int num[ ]) { int i; for(i=0; i<10;i++) printf(“%d”, num[i]); } 3. It may be declare as a pointer of array; #include <stdio.h> void main(void) { int t[10], i; for(i=0; i<10; ++i) t[i]=i; display(t); } void display(int *num) { int i; for(i=0; i<10;i++) printf(“%d”, num[i]); } • It may be declare as an array; #include <stdio.h> void main(void) { int t[10], i; for(i=0; i<10; ++i) t[i]=i; display(t); } void display(int num[10]) { int i; for(i=0; i<10;i++) printf(“%d”, num[i]); }

  8. Example • #include <stdio.h> • #include <ctype.h> • void print_upper(char *string); • void main(void) • { • char s[80]; • gets(s); • print_upper(s); • } /*print a string in uppercase. */ void print_upper(char string[ ]) { int t; for(t=0; string[t]; ++t) { string[t] = toupper(string[t]); putchar(string[t]); } printf("\n"); }

  9. argc and argv – Arguments to main( ) • Generally, we pass information into main() function via command line arguments. argc; holds the number of arguments on the command line. argv; is a pointer to an array of character pointers. #include <stdio.h> #include <stdlib.h> void main(int argc, char *argv[ ]) { if(argc != 2) { printf("you forgot to type your name \n"); exit(1); } printf("Hello %s\n ", argv[1]); printf("Program name is %s\n", argv[0]); printf("The count of the input word %d \n", argc); }

  10. #include <stdio.h> • #include <stdlib.h> • #include <ctype.h> • #include <string.h> • void main(int argc, char *argv[ ]) • { • int disp, count; • if (argc < 2 ){ • printf("You must enter the length of the count \n"); • printf("on the commant line. Try again. \n"); • exit(1); • } • if (argc == 3 && !strcmp(argv[2], "display")) disp = 1; • else disp = 0; • for(count=atoi(argv[1]); count; - - count) • if (disp) printf("%d \n", count); • printf("done \n"); • }

  11. The return Statement • The return statement has two important usage; • It couses an immediate exit from the function and the program execution pass to the calling code. • It may be used to return a value to the calling procedure.

  12. /* Return index of first match of s2 in s1. */ • find_substr(char *s1, char *s2) • { • int t; • char *p, *p2; • for(t=0; s1[t]; t++) { • p= &s1[t]; • p2=s2; • while(*p2 && *p2==*p) { • p++; • p2++; • } • if (!*p2) return t; • } • return -1; • }

  13. Returning The Values • All functions, except those of type void, return a value. • This value is specified by the return statement. • The functions can be three types; • Simply computational; these functions are specifically designed to perform operations on their arguments and return a value based on that operation. ( Exmp: sqrt( ) or sin( ) ). • The second type of functions; manipulates information and returns a value that simply indicates the success or failure of that manipultion. (Examp: fclose( )..). • The last typeof function has no explicit return value. (Examp: exit( ) ).

  14. #include <stdio.h> • int mul(int a, int b); • void main(void) • { int x, y, z; • x=10; y=20; • z=mul(x,y); /* return value assign to z. */ • printf("%d \n", mul(x,y)); /* return value is used by the printf( ) function. */ • mul(x,y); /* return value is lost. */ • } • mul(int a, int b) • { • return a*b; • }

  15. Function Prototype • When you use prototypes, C can find and report any illegal type convertions between the type of arguments used to call a function and the type definition of its parameters. • The general form of a function prototype definition is; type func_name(type parm_name1,..., type parm_nameN); #include <stdio.h> void sqr_it(int i); /* prototype */ void main(void) { int x; x=10; sqr_it(x); /* ?? */ printf("%d \n", x); } void sqr_it(int *i) { *i = *i * *i; }

  16. Return Non-integer Values • When the type of function is not declared, it automatically defaults to integer. • For the non-integer values; the function must be given an explicit type specifier and type of function must be identified before the first call made to it. #include <stdio.h> float sum(); /* identify the function */ void main(void) { float first, second; first = 123.23; second = 99.09; printf("%f \n", sum(first, second)); } float sum(float f, float s) { return (f + s); }

  17. Returning Pointers • #include <stdio.h> • char *match(char c, char *s); /* prototype */ • void main(void) • { char s[80], *p, ch; • gets(s); • ch = getchar(); • p=match(ch, s); • if(*p) /* there is a match */ • printf("%s \n", p); • else • printf("no match found \n"); • } • char *match(char c, char *s) • { while(c != *s && *s) s++; • return s; • }

  18. Lab. Exercise #1 • Write a program to find the number of times that a given word (i.e. a short string) occurs in a sentence (i.e. a long string!). • Read data from standard input. The first line is a single word, which is followed by general text on the second line. • Typical output should be: The word is "the". The sentence is "the cat sat on the mat". The word occurs 2 times.

  19. Recursion • There are two approaches to writing repititive algorithms: • Iteration • Recursion; is a repititive process in which an algorithm call itself. Definition: The recursive solution for a problem involves a two-way journey: 1. Decompose the problem from the top to the bottom. 2. Solve the problem from the bottom to the top.

  20. Recursive Functions • The general form of a function is; void recurse() { recurse(); //Function calls itself } int main() { recurse(); //Sets off the recursion return 0; //Rather pitiful, it will never be reached } • Recursion is defined as a function calling itself. • It is in some ways similar to a loop because it repeats the same code, but it requires passing in the looping variable and being more careful.

  21. Recursive Functions • Recursive program will not continue forever. • The computer keeps function calls on a stack and once too many are called without ending, the program will terminate. • Let write a program to see how many times the function is called before the program terminates? #include <iostream.h> void recurse(int count) /*The count variable is initalized by each function call */ { printf(“%d”, count); recurse(count+1); /* It is not necessary to increment count each */ /* function's variables */ } /*are separate (so each count will be initialized one greater) */ int main() { recurse(1); /*First function call, so it starts at one return 0; */ }

  22. Recursive Functions • Recursive functions can be thought of like the Russian dolls that always have a smaller doll inside. Each doll calls another doll, and we can think of the size being a counter variable that is being decremented by one. • Think of a really tiny doll, the size of a few atoms. We can't get any smaller than that, so there are no more dolls. • Normally, a recursive function will have a variable that performs a similar action; one that controls when the function will finally exit. The condition where the function will not call itself is termed the base case of the function. • Basically, it is an if-statement that checks some variable for a condition (such as a number being less than zero, or greater than some other number) and if that condition is true, it will not allow the function to call itself again. (Or, it could check if a certain condition is true and only then allow the function to call itself).

  23. Example • void doll(int size) • { if(size==0) /* No doll can be smaller than 1 atom (10^0==1) so doesn't call /* itself • return; • /* Return does not have to return something, it can be used • /* to exit a function • doll(size-1); /* Decrements the size variable so the next doll will be smaller. • } • int main() • { • doll(10); /*Starts off with a large doll (its a logarithmic scale) • return 0; /*Finally, it will be used • }

  24. Sample Algorithm • /*The power algorithm */ • program TestPower • 1. read base, exp • 2. result = power(base, exp) • 3. print result • end TestPower • algorithm Power(base, exp) • num=1 • loop(exp > 0) • num=num*base • exp=exp-1 • return num

  25. Sample Algorithm base=5 exp=2 • /*The recursive power algorithm */ • program Power(int base, int exp) • Pre base is the number to be raised • exp is the exponent • Post value of base **exp computed • Return value of base**exp returned • if (exp equal 0) • return(1) • else • return (base*power(base, exp-1)) • endpower return 25 Power(5,2) return 5 Power(5,1) Power(5,2) return 1 Power(5,0) Power(5,1) Power(5,2)

  26. Recursive Functions • Once a function has called itself, it will be ready to go to the next line after the call. • It can still perform operations. • One function we could print out the numbers 123456789987654321. • How can we use recursion to write a function to do this? Simply have it keep incrementing a variable passed in, and then output the variable...twice, once before the function recurses, and once after...

  27. Example • void printnum(int begin) • { • printf(“%d”, begin); • if(begin<9) /*The base case is when begin is greater than 9 • printnum(begin+1); /*for it will not recurse after the if-statement • printf(“%d”, begin); /*Outputs the second begin, after the program has • /*gone through and output • }/*the numbers from begin to 9. • void main( ) • { • printnum(1); • } The output is; 123456789987654321

  28. Lab. Exercise #2 • Use recursion to write a program that returns the factorial of any number greater than 0. Factorial is number*(number-1)*(number-2)...*(1)

  29. Homework • Write a C code to tell the user whether a number is polindrome. • (A polindrome is a number that is the same written both forward and backward, such as 81318). • Create two solutions: • 1. use recursion function structure and call by reference technique, and • 2. use not recursion function structure and call by value technique. Upload to FTP until December 21th. 2006 at 17:00

  30. Next Course • Structures, Unions, Enumarations and User-Defined Types...

More Related