1_pdfsam_cs2022

# 1_pdfsam_cs2022 - Recursion is a powerful technique for...

This preview shows pages 1–6. Sign up to view the full content.

Call by value Function arguments in C are passed by value The value of the argument is passed, not a reference Functions are given a new copy of their arguments So a function can’t modify the value of a variable in the calling function (unless you use pointers) int F( int a ) { a=0; return a; } void main() { int A = 1, B; B = F(A); printf( "%d %d\n”, A, B ); // prints “1 0” }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Call by value Example void swap ( int a, int b ) { int temp = a; a = b; b = temp; } void main() { int A = 1, B = 2; swap(A, B); printf( "%d %d\n”, A, B ); }
Call by value Call by value has advantages and disadvantages Advantage: some functions are easier to write Disadvantage: sometimes you’d like to modify an argument (e.g. a swap() function) We’ll see how to do this using pointers later int power(int base, int exp) { int result = 1; for( ; exp >= 1 ; exp--) result *= base; return base; }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Recursion

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Recursion is a powerful technique for specifying sets, functions, and programs A recursive function is a function that refers to itself Many algorithms can be written more compactly, easily, elegantly using recursion Early languages (e.g. Fortran) did not support recursion C and most other modern languages do Recursion is possible because of the execution stack Recursion example Example: computing positive integral powers a n = aaaa (n times) Recursive definition: a = 1, a n+1 = aa n int power(int base, int exp) { if(exp == 0) return 1; else return base*power(base, exp-1); } int main(void) { printf(%d\n, power(5, 2)); return 0; } Lecture 4 today Last week: Things you already knew. This week: Things you come to this class for. Drop deadline: Today!...
View Full Document

## This note was uploaded on 01/10/2010 for the course CS 2022 taught by Professor Crandall during the Fall '08 term at Cornell University (Engineering School).

### Page1 / 6

1_pdfsam_cs2022 - Recursion is a powerful technique for...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online