introduction to computer algorithmics and programming ceng 113 functions and recursive functions

30
Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

Upload: jane-harrison

Post on 02-Jan-2016

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

Introduction to Computer Algorithmics and Programming

Ceng 113

Functions and Recursive Functions

Page 2: 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

}

• 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.

Page 3: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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.

Page 4: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

Scope Rules of Functions

1. Each function is discrete block of code (for instance, you cannot

use goto to jump into middle of another function).

2. 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.

3. You cannot define a function within a function.

4. 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.

Page 5: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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;

}

Page 6: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

call by value / call by referenceSubroutines can be passed arguments in one of two ways;

1. Call by value; This method copies the value of an argument into the formal parameter of the subroutine.

2. Call by reference; In this method, the address is used to access the actual argument used in the call.

#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;}

#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;}

Page 7: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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:

1. 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]);}

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]);}

Page 8: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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");

}

Page 9: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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);

}

Page 10: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

#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");

}

Page 11: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

The return Statement

The return statement has two important usage;

1. It couses an immediate exit from the function and the

program execution pass to the calling code.

2. It may be used to return a value to the calling procedure.

Page 12: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

/* 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;

}

Page 13: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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( ) ).

Page 14: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

#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;}

Page 15: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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;}

Page 16: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

Return Non-integer ValuesWhen 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);}

Page 17: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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;}

Page 18: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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.

Page 19: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

RecursionThere are two approaches to writing repititive algorithms:

1. Iteration

2. 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.

Page 20: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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.

Page 21: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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; */

}

Page 22: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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).

Page 23: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

Examplevoid 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

}

Page 24: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

Sample Algorithm/*The power algorithm */program TestPower1. read base, exp2. result = power(base, exp)3. print resultend TestPower

algorithm Power(base, exp)1. num=12. loop(exp > 0)

1. num=num*base2. exp=exp-1

3. return num

Page 25: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

Sample Algorithm

/*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

Power(5,2)

Power(5,2)

Power(5,1)

Power(5,2)

Power(5,1)

Power(5,0)

base=5exp=2

return 1

return 5

return 25

Page 26: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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...

Page 27: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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

Page 28: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

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)

Page 29: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

HomeworkWrite 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

Page 30: Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

Next Course

• Structures, Unions, Enumarations and User-Defined Types...