Functions Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2013 Instructor: Dr. Asish Mukhopadhyay

Similar documents
Course organization. Course introduction ( Week 1)

Course organization Course introduction ( Week 1) Part I: Introduction to C programming language (Week 3-12)

Course organization. Part I: Introduction to C programming language (Week 1-12) Chapter 1: Overall Introduction (Week 1-4)

Chapter 4 Functions By C.K. Liang

1.7 Recursion. Department of CSE

Lecture 9 - C Functions

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

CSCI 2132 Software Development. Lecture 17: Functions and Recursion

Chapter 3. Functions

Arrays and Applications

Chapter 3. Functions

15 FUNCTIONS IN C 15.1 INTRODUCTION

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

CSCI 2132 Software Development. Lecture 18: Functions

Functions. Chapter 5

CS 161 Intro to CS I. Finish Pointers/Start Recursion

Programming Language A

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

BSM540 Basics of C Language

CSCI 2132 Software Development. Lecture 20: Program Organization

Structured Programming. Functions and Structured Programming. Functions. Variables

Introduction to Programming

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

CSE 230 Intermediate Programming in C and C++ Functions

Computer Programming: Skills & Concepts (CP) Variables and ints

CS113: Lecture 4. Topics: Functions. Function Activation Records

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

Programming Language B

Programming Language A

SOFTWARE Ph.D. Qualifying Exam Fall 2017

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

'C' Programming Language

Function Calls. Tom Kelliher, CS 220. Oct. 24, SPIM programs due Wednesday. Refer to homework handout for what to turn in, and how.

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

Midterm Exam. CSCI 2132: Software Development. March 4, Marks. Question 1 (10) Question 2 (10) Question 3 (10) Question 4 (10) Question 5 (5)

Programming & Data Structure Laboratory. Day 2, July 24, 2014

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Characters and Strings

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Lab 3. Pointers Programming Lab (Using C) XU Silei

This is CS50. Harvard University Fall Quiz 0 Answer Key

More Recursive Programming

Chapter 7 Functions. Now consider a more advanced example:

Functions. (transfer of parameters, returned values, recursion, function pointers).

Lecture 6. Statements

Chapter 10: Recursive Problem Solving

Computer Programming for Engineering Applica4ons. Intro to Programming 10/2/13 ECE 175. Limita4ons of Reference by Value. The Concept of Pointers

Inductive Definition to Recursive Function

More examples for Control statements

Functions. Arash Rafiey. September 26, 2017

Dalhousie University CSCI 2132 Software Development Winter 2018 Midterm Examination II March 12 15:37-16:24

ECE 2574: Data Structures and Algorithms - Recursion Part I. C. L. Wyatt

Introduction to C. CS2023 Winter 2004

Function Calls. 1 Administrivia. Tom Kelliher, CS 240. Feb. 13, Announcements. Collect homework. Assignment. Read

CS 310 Advanced Data Structures and Algorithms

Decision Making and Loops

Part II Answer to all the questions (2 Marks):

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

Unit 7. Functions. Need of User Defined Functions

Practice Sheet #07 with Solutions

PERIYAR CENTENARY POLYTECHNIC COLLEGE Periyar Nagar- Vallam Thanjavur

Procedural programming with C

Structured programming

Multiple Choice Questions ( 1 mark)

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Programming Language B

ARRAYS(II Unit Part II)

Chapter 15: Recursion

EK131 E5 Introduction to Engineering

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Array Initialization

CSE 303 Lecture 8. Intro to C programming

Lecture 04 FUNCTIONS AND ARRAYS

Recursion. Data and File Structures Laboratory. DFS Lab (ISI) Recursion 1 / 20

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

C: How to Program. Week /Apr/16

MODULE 2: Branching and Looping

CS240: Programming in C

Decision Making -Branching. Class Incharge: S. Sasirekha

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Q1 (15) Q2 (15) Q3 (15) Q4 (15) Total (60)

FUNCTIONS. Without return With return Without return With return. Example: function with arguments and with return value

Basic and Practice in Programming Lab7

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

CSCI 2132 Software Development. Lecture 19: Generating Permutations

Solutions to Assessment

Fundamentals of Programming Session 14

Learning C Language. For BEGINNERS. Remember! Practice will make you perfect!!! :D. The 6 th week / May 24 th, Su-Jin Oh

Slide Set 1. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

LAB 7 FUNCTION PART 2

Please note that, for all What will be output questions, the answer could be error or indefinite. However, there is no compile error.

Computer Programing. for Physicists [SCPY204] Class 02: 25 Jan 2018

ESC101N: Fundamentals of Computing End-sem st semester

C Programming Lecture V

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #06

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

Questions Bank. 14) State any four advantages of using flow-chart

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Transcription:

Functions 60-141 Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2013 Instructor: Dr. Asish Mukhopadhyay

Motivation

A complex program Approximate Ellipse Demo Ellipse2DDouble.java GeometryUtils.java Main.java MinCircleApprox.java MinEllipse.java MinEllipseApplet.java MinEllipseApprox.java MinEllipseFrame.java Vector2DDouble.java

Program Complexity How do we manage it? Break up the computation into manageable pieces : a paradigm common to programming languages These pieces (or modules) are called functions in C C-functions can be user-defined or defined in the C Standard Library Establish a protocol for communication among the various functions

Function Basics Problem: Compute the Greatest Common Divisor (GCD) of two positive integers m and n Task decomposition Read input Compute GCD Print GCD

Function Basics 1. #include <stdio.h> 2. int gcd(int, int);// function prototype 3. int main (void) { 4. int m, n; //variables to store input // numbers 5. scanf("%d %d", &m, &n); //read input 6. printf("the gcd of %d and %d is: %d", m, n, gcd(m, n)); // print input 7. return 0; } // end main Function call

GCD function /* definition of the gcd function */ int gcd(int m, int n) { int rem; rem = m%n; /*loop until remainder is 0 */ while(rem!= 0) { m = n; // reset m and n n = rem; rem = m % n; } // end while return n;

Learning Points?

Function definition format return-type function-name (argument declarations) { declarations and statements }

Function definition format Various parts may be absent If return-type is omitted, int is assumed A minimal function (does and returns nothing) is : dummy() {}

Argument declarations A function is essentially an operator, though in a more general sense than the binary operators like +, -, *, etc. Operands are provided through the argument list

Return statement (1) The return statement is a mechanism for returning a value (result of an operation, we might say) from the called function to the caller Syntax: return expression

Return statement (2) Any expression can follow return If necessary, its type is converted to that of the return type of the function If expression is absent then nothing is returned and control is turned to the caller when the function execution reaches the closing bracket

Function declarations Also known as function prototypes Placed at the beginning of the source file Subsequent definitions and function calls must match the declarations Facilitates error-checking by compiler and type-coercion

Function types User-defined gcd(m,n), for example Library functions scanf( ) printf( )

Reinforce. Class-work: Problem: Write a modular C-program to determine if a given positive integer is a palindromic string

Palindrome program int palindrome(int number) { int new_number, temp; new_number = 0; temp = number; while(temp >0) { /* loop until number becomes 0 */ new_number = new_number*10 + temp % 10; temp = temp /10; } return (number == new_number); } // palindrome

Palindrome program #include <stdio.h> int palindrome(int); // function prototype int main(void) { int number; scanf("%d", &number); /*read in number */ if (palindrome(number)) printf("number is palindrome\n"); else printf("number is not palindrome\n"); } // end of main

A more complex problem (1) Problem: Print each line of a text that contains a given pattern

A more complex problem (2) Thus if pattern = area and the text is My research area is theoretical computer science Many interesting problems to work on in this area I love working in this field The output is: My research area is theoretical computer science Many interesting problems to work on in this area

Example (2) Task decomposition while (there s another line) if (the line contains the pattern) print it

Example #include <stdio.h> #define MAXLINE 1000 /* maximum input line length */ // function prototypes int getline(char line[], int max); int strindex(char source[], char searchfor[]); // pattern to search for char pattern[] = area";

Example (3) /*find all lines matching pattern*/ int main (void) { char line[maxline] int found = 0; } while (getline(line, MAXLINE) >0) if (strindex(line, pattern) >= 0) { printf( %s, line); found++; } return found;

Example (4) getline(line, MAXLINE) /*getline: get line into s, return length*/ int getline(char s[], int lim) { int c, i; i= 0; while (--lim > 0 && (c = getchar())!=eof && c!= \n ) s[i++] = c; if (c == \n ) s[i++] = c; s[i] = \0 ; return i; }

Example (4) strindex(line, pattern) /* strindex: return index of t in s, -1 if none */ int strindex(char s[], char t[]) { int i, j, k; for (i=0; s[i]!= \0 ; i++) { for (j=i, k=0; t[k]!= \0 && s[j] == t[k]; j++, k++); if (k > 0 && t[k] == \0 ) return i; } return -1; }

Another Example /* atof: convert string s to double */ double atof(char s[]) { double val, power; int i, sign; for (i=0; isspace(s[i]); i++); /* skip white spaces */ sign = (s[i] == '-')? -1: 1; if (s[i] == '+' s[i] == '-') i++; for (val = 0.0; isdigit(s[i]); i++) val = 10.0 * val + (s[i] - '0'); if (s[i] = '.') i++; for (power = 1.0; isdigit(s[i]); i++){ val = 10.0 * val + (s[i] - '0'); power *= 10.0; } return sign * val/power; }

Learning Points?

Function Basics C-Functions Cannot be nested Can call each other (itself?) Communicate through Arguments Return values External (global) variables Can occur In any order in a source file Can be distributed across multiple source files

Function Basics Any C- program consists of a set external objects What are these?

External Objects All functions, as C does not permit nesting of functions Variables declared outside all functions These allow communication between different functions This comes with a warning! Undisciplined use can lead to serious programming errors

Point to Note In contrast, variables inside a function definition are called automatic (or local) variables Function parameters are also in effect local variables

Scope Rules (1) The scope of a name (identifier) is the part of the program within which the name can be used Thus the scope of an automatic variable (local variable) is the function in which it is declared External variable or function is from the point where it is declared to the end of the file being compiled

Scope Rules (2) If an external variable is to be referred to before it is defined or is defined in a different source file then, an extern declaration is mandatory Let s see an example.

#include <stdio.h> An example void f(void); // function prototype extern int i; // declaring i before definition int main(void) { printf("the value of i is: %d\n", i); f(); return 0; } int i = 1; // scope of i is the rest of the program void f(void) { printf("the value of i is: %d\n", i); }

Example (1) This program prints 1, following scope rules #include <stdio.h> int i = 0; int main(void) { int i = 1 printf("%d", i); return 0; }

Example (2) This program prints 0, following rules for external variables #include <stdio.h> int i = 0; int main(void) { extern int i; printf("%d", i); return 0; }

Example (3) This program also prints 0, as the reference is to the external variable i #include <stdio.h> int i = 0; int main(void) { printf("%d", i); return 0; }

Static variables Static declaration applied to an external variable limits the scope of the variable to the file being compiled a function limits the visibility of the function to the file in which it is declared an internal variable makes the variable remain in existence rather than be transient with function activation

Register variables Declaration Syntax: register int x; register char x; Indicates to the compiler that the variables will be heavily used ; so, placing them in machine registers will result in faster programs Only automatic variables and function arguments can be thus declared There is an upper limit on the number of such variables

Block Structure Despite no function-nesting, variables can be declared inside a function in a block-structure fashion thus: if (n > 0) { int i; /* declare a new i */ for (i=0; i < n; i++). } i remains in existence until }, and any identically named variable outside the block is hidden from the scope of the block

Recursion A C-function can call itself to implement a recursive computation Consider this problem: Print an integer number as a character string Discounting the sign of the number, the difficulty here is that while the printing must be done from left to right the digits can be extracted from right to left

Printing Solution #include <stdio.h> /*printd: print n in decimal */ void printd(int n) { if(n < 0) { putchar( - ); n = -n; } // end of if If (n/10) printd(n/10); // call to printd with a smaller argument putchar(n%10 + 0 ); } // end of printd

Points to Note The function printd (n) calls itself with a smaller value, viz., n/10 if it is greater than 0 (inductive step) else prints the one-digit number (base step) This is characteristic of a recursive function Each invocation gets a fresh set of automatic variables, independent of the previous set Recursive code is compact but not necessarily faster or space-saving

Unwinding the recursion printd(n/10) n = 123 print n% 10 = 3 return printd(n/10) n = 12 print n % 10 = 2 return int main(void) {... printd(123);.. } printd(n/10) n = 1 print 1 return

Recursive Computation: Another example Consider this computation: factorial(n) = n* factorial(n-1), n >= 1 factorial(0) = 1 Characteristic features: Can t know what is factorial(n) until we know factorial(n-1),.. That factorial(0) = 1 helps us compute factorial(n) by going backwards

C-program for n! long factorial(int n) { if (n == 0) return 1; else return (n*factorial(n-1)); } // end of factorial

Activation stacks 5! 5 * 4! 4 * 3! 3* 2! 2* 1! 5! 5 * 4! 4 * 3! 3* 2! 5!= 5* 24 = 120 is returned 2* 1! 4!= 4* 6 = 24 is returned 3!= 3* 2 = 6 is returned 2!= 2 * 1 is returned 1 1 1 is returned

Tower of Hanoi 13/08/2013 48 Dr. Asish Mukhopadhyay, School of Computer Science, Univ. of Windsor

Tower of Hanoi 13/08/2013 49 Dr. Asish Mukhopadhyay, School of Computer Science, Univ. of Windsor

Tower of Hanoi Rule 1 We can move only one disk at a time Rule 2 We may not place a larger disk atop a smaller one in any move 13/08/2013 50 Dr. Asish Mukhopadhyay, School of Computer Science, Univ. of Windsor

Recursive solution 13/08/2013 51 Dr. Asish Mukhopadhyay, School of Computer Science, Univ. of Windsor

Number of moves? 2 n - 1 Proof?!!!!! Again!!! 13/08/2013 52 Dr. Asish Mukhopadhyay, School of Computer Science, Univ. of Windsor

printf("input the number of pegs:"); scanf("%d", &numberofpegs); printf("\n"); generatemoves(numberofpegs, pega, pegb, pegc); } C-program for Tower of Hanoi #include <stdio.h> void generatemoves(int, int, int, int); int main(void) { int numberofpegs; int pega = 1; int pegb = 2; int pegc = 3;

void generatemoves(int numberofpegs, int pega, int pegb, int pegc) { //if (numberofpegs == 0) printf("this is the end of all moves \n"); if (numberofpegs == 0) return; else{ generatemoves(numberofpegs - 1, pega, pegc, pegb); printf("move disk from %d to %d\n\n", pega, pegc); generatemoves(numberofpegs - 1, pegb, pega, pegc); } }

Function call Activation Frames Just as a recursive C program is implemented using a stack of activation calls, functions calling each other is also implemented using a stack frame

Example Operating System int main() R1 { int a = 10; printf( %d squared: %d\n, a, square(a)) } Stack top Return Location R1 Automatic variables a 10 Stack frame for function main

Example Stack top int main() Return Location R2 Automatic variables x 10 Stack frame for function square R2 { int a = 10; printf( %d squared: %d\n, a, square(a)) } Return Location R1 Automatic variables int square( int x ) a 10 Stack frame for function main { } return x*x

Yet another example Write a C-program to reverse a string in place recursively

C-program #include <stdio.h> #include <string.h> void reverser(char *, int, int); // function prototype int main(void) { } char s[] = "abcde"; reverser(s, 0, strlen(s)); printf("%s\n", s);

C-Program (2) void reverser(char *s, int i, int len) { int c, j; j = len - (i+1); //printf("j is %d: \n", j); } if(i < j) { c = s[i]; s[i] = s[j]; s[j] = c; reverser(s, ++i, len); } else return;

To do Read Chapter 5 of your Deitel and Deitel text, focussing on the worked out examples Solve as many self-review exercises as you can Next lecture on arrays and pointers (maybe)