Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions and Recursion

Similar presentations


Presentation on theme: "Functions and Recursion"— Presentation transcript:

1 Functions and Recursion
By Hector M Lugo-Cordero September 10, 2008 Department of Electrical and Computer Engineering

2 The Department of Electrical and Computer Engineering
Outline Functions Parameters Return Value Recursion Base Case Process Stack The Department of Electrical and Computer Engineering

3 The Department of Electrical and Computer Engineering
Functions Functions A function is a piece of code that performs specific tasks Allows code reuse Syntax <return_type> <name_of_function>(<params>){ //code goes here [return statement] } Functions can be declared before or after main The Department of Electrical and Computer Engineering

4 The Department of Electrical and Computer Engineering
Recursion Recursion Recursion is the act of a function calling itself The computer can easily run out of memory Thus the base case is then introduced Indicates when the function will stop calling itself Each function run has a different process stack The Department of Electrical and Computer Engineering

5 The Department of Electrical and Computer Engineering
Examples Write a function that simulates Windows system(“pause”) command for a Linux computer. void pause(){ … } Write a function that compares two integers int compare(int x, int y){ … } This funcion returns 1 if x is greater than y 0 if x is equal to y -1 if x is less than y The Department of Electrical and Computer Engineering

6 The Department of Electrical and Computer Engineering
Examples (cont.) Write a function that checks if a number is prime or not bool isPrime(int num){ … } The function checks if num is 2 if so returns true If not then it verifies if the number is even in which case returns false if it is Finally if none of these conditions are met then it starts dividing num by 3, 5, 7, … until it finds that any of these divides the number, in which case returns false The function returns true if the divisor is greater than the square root of the number The Department of Electrical and Computer Engineering

7 The Department of Electrical and Computer Engineering
Questions? ? The Department of Electrical and Computer Engineering


Download ppt "Functions and Recursion"

Similar presentations


Ads by Google