CSCI 2132 Software Development. Lecture 17: Functions and Recursion

Similar documents
CSCI 2132 Software Development. Lecture 18: Functions

CSCI 2132 Software Development. Lecture 19: Generating Permutations

CSCI 2132 Software Development. Lecture 20: Program Organization

CSCI 2132 Software Development Lecture 18: Implementation of Recursive Algorithms

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

Functions. Arash Rafiey. September 26, 2017

CSCI 2132 Software Development. Lecture 14: Software Development Life Cycle

BSM540 Basics of C Language

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

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

CSCI 2132 Software Development. Lecture 8: Introduction to C

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

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

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

Functions BCA-105. Few Facts About Functions:

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

Lecture 9 - C Functions

Computer Science & Engineering 150A Problem Solving Using Computers

CSCI 2132 Software Development. Lecture 29: Dynamic Memory Allocation

Code No: R Set No. 1

We can use a max-heap to sort data.

27-Sep CSCI 2132 Software Development Lecture 10: Formatted Input and Output. Faculty of Computer Science, Dalhousie University. Lecture 10 p.

25.2 Opening and Closing a File

Computer Programming: C++

We first learn one useful option of gcc. Copy the following C source file to your

Final Exam 1 /12 2 /12 3 /10 4 /7 5 /4 6 /10 7 /8 8 /9 9 /8 10 /11 11 /8 12 /10 13 /9 14 /13 15 /10 16 /10 17 /12. Faculty of Computer Science

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

CSCI 2132 Software Development Lecture 35: Dynamically Allocated Arrays, Course Review

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

Topics Recursive Sorting Algorithms Divide and Conquer technique An O(NlogN) Sorting Alg. using a Heap making use of the heap properties STL Sorting F

Structured programming

C Programming Language

Solution for Data Structure

Principles of Programming. Chapter 6: Arrays

Sorting. Task Description. Selection Sort. Should we worry about speed?

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Solutions to Assessment

Chapter 9: Functions. Chapter 9. Functions. Copyright 2008 W. W. Norton & Company. All rights reserved.

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

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

CSE 230 Intermediate Programming in C and C++ Functions

Computer Programming

Subject: Fundamental of Computer Programming 2068

DATA STRUCTURES AND ALGORITHMS

Binding and Variables

CS16 Exam #1 7/17/ Minutes 100 Points total

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

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

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

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Arrays and Applications

Chapter 7 Functions. Now consider a more advanced example:

CSCE 2014 Final Exam Spring Version A

Welcome! COMP s1. Programming Fundamentals

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers

AMCAT Automata Coding Sample Questions And Answers

Functions. Functions. Identify Repeated Code. Identify Repeated Code. Identify Similar Code. Use Parameters to Customize 2/25/14

Tutorial 5. Call Stack and Stack Frames. Memory Addresses and Pointers. Content vs Address of Pointers. scanf() function. Perils of Pointers

CSE101-Lec#18. Multidimensional Arrays Application of arrays. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

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

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

Lecture 6 Sorting and Searching

Introduction to Computing Lecture 09: Functions (Part II)

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Unit 7. Functions. Need of User Defined Functions

Programming Studio #9 ECE 190

User Defined Functions

Computer Systems Lecture 9

1 Dynamic Memory continued: Memory Leaks

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

Fundamental of Programming (C)

Technical Questions. Q 1) What are the key features in C programming language?

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

18-Sep CSCI 2132 Software Development Lecture 6: Links and Inodes. Faculty of Computer Science, Dalhousie University. Lecture 6 p.

Lecture 3: C Programm

Tutorial 6. Memory Addresses and Pointers. scanf() function. Perils of Pointers. Function Pointers. Declarations vs. Definitions

This is CS50. Harvard University Fall Quiz 0 Answer Key

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

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

A brief intro to pointers for the purposes of passing reference parameters

(Refer Slide Time 01:41 min)

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

(Section : Computer Science)

Pointers, Arrays and Parameters

EE 368. Weeks 4 (Notes)

It is necessary to have a single function main in every C program, along with other functions used/defined by the programmer.

Unit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.

SUHAIL T A

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

Data Structures And Algorithms

Dynamic memory allocation

Array Initialization

CSC 270 Survey of Programming Languages. What is a Pointer?

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

C programming basics T3-1 -

COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

Quiz 0 Answer Key. Answers other than the below may be possible. Multiple Choice. 0. a 1. a 2. b 3. c 4. b 5. d. True or False.

Transcription:

CSCI 2132 Software Development Lecture 17: Functions and Recursion Instructor: Vlado Keselj Faculty of Computer Science Dalhousie University 15-Oct-2018 (17) CSCI 2132 1

Previous Lecture Example: binary search Multidimensional arrays Variable-length arrays Example: Latin square 15-Oct-2018 (17) CSCI 2132 2

Functions The main code abstraction method: sequence of statements that can be called by a name; i.e., executed Functions have arguments and usually return a value, and that is where name comes from Function definition example int max(int a, int b) { int c; c = (a > b)? a : b; return c; } 15-Oct-2018 (17) CSCI 2132 3

int by default Function Return Value Not necessary; can use: void An array cannot be return value Example of calling a function: printf("%d\n", max(a,b) ); Some known examples of functions: Return value of printf: number of printed characters Return value of scanf: number of converted values (or, EOF if error or mismatch occurs before the first value is converted) 15-Oct-2018 (17) CSCI 2132 4

Example with scanf if ( 2!= scanf("%d %d", &i, &j) ) { printf("invalid input\n"); return 1; } 15-Oct-2018 (17) CSCI 2132 5

Function Declarations or Function Prototypes Used to declare function argument types and return type before defining the body of the function Needed if we call function in source code before being defined, so that compiler does not need to guess Syntax: return-type function-name(parameters); Example: int max(int a, int b); or: int max(int, int); 15-Oct-2018 (17) CSCI 2132 6

#include <stdio.h> An Example int max(int a, int b); int main(void) { int a = 5, b = 4; printf("%d\n", max(a,b)); return 0; } int max (int a, int b) { return (a < b)? a : b; } 15-Oct-2018 (17) CSCI 2132 7

Arguments Arguments vs. parameters Similar terms and frequently used interchangeably Strictly speaking, they are different Arguments, or actual parameters: Expressions used in function call; e.g.: max( a, 3+(b-1)/2 ); Parameters, or formal parameters: Variables used in function definition; e.g.: int max( a, b ) { return (a < b)? a : b; } 15-Oct-2018 (17) CSCI 2132 8

Arguments Passed by Value Arguments in programming languages can be passed: by value by reference and few other variations Arguments in C are passed by value Arrays behave in a special way they appear to be passed by reference however, they are still passed by value, but as pointers to be better explained later 15-Oct-2018 (17) CSCI 2132 9

Code Example void swap (int a, int b) { int temp = a; a = b; b = temp; }... int a = 4; int b = 5; swap(a, b); printf("a=%d, b=%d\n", a, b); 15-Oct-2018 (17) CSCI 2132 10

Passing Array Parameters Functions cannot tell the length of an array parameter Usually need to pass array length as another parameter For example: int max_array(int, int []); int max_array(int len, int a[]) {... } 15-Oct-2018 (17) CSCI 2132 11

Call Stack: Process Memory Partition What happens when a function is called? Remember memory partition: code, data, stack, heap Code: stores program code Data: stores static data; e.g., #include <stdio.h> int A[10][10], Asize; /* Static variables */ int main() { scanf("%d", &Asize); /* etc... */ return 0; } 15-Oct-2018 (17) CSCI 2132 12

Use of Stack: Call Stack Have not seen yet how stack and heap are used Call stack is a stack in data structures sense Important in the context of function calling and local variables Call stack keeps information about active functions; i.e., functions being executed Whenever function starts execution: new stack frame is pushed on stack; also called activation record Contains information such as: arguments, local variables, return value, return instruction pointer, previous stack base address 15-Oct-2018 (17) CSCI 2132 13

Example Assume that function main calls function max The call stack would look as follows: top of the stack max main stack frame of function max stack frame of function main 15-Oct-2018 (17) CSCI 2132 14

Recursion Let us see what role the call stack plays in recursion Consider the following example: int power(int x, int n) { if (n == 0) /* Base case */ return 1; else /* Recursive case */ return x * power(x, n-1); } Let us assume that power(3,4) is called from main 15-Oct-2018 (17) CSCI 2132 15

Call Stack: power(3,4) power(3,0) power(3,1) power(3,2) power(3,3) power(3,4) main Each call adds a new stack frame After each function return, a stack frame is popped 15-Oct-2018 (17) CSCI 2132 16

Merge Sort Example Divide-and-conquer paradigm: Divide: Divide the n-element array to be sorted into two subarrays of n/2 elements each. Conquer: Sort the two subarrays recursively using the same algorithm: merge sort Combine: Merge the two sorted subarrays to produce the sorted answer. 15-Oct-2018 (17) CSCI 2132 17

Merge Sort: Example Let us consider the following array of 10 elements: ( 9, 7, 14, 2, 3, 19, 11, 5, 1, 15 ) We divide the array into two approximately equally long-subarrays: ( 9, 7, 14, 2, 3) and (19, 11, 5, 1, 15 ) We assume that these subarrays are sorted, which is exactly the same task with smaller arrays, so we get: ( 2, 3, 7, 9, 14) and (1, 5, 11, 15, 19 ) Now, we can get the final sorted array using a merge operation 15-Oct-2018 (17) CSCI 2132 18

Example of a Merge Procedure Starting configuration: 2 3 7 9 14 1 5 11 15 19 In process: 7 9 14 1 2 3 5 11 15 19 15-Oct-2018 (17) CSCI 2132 19