Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

C Language.
Chapter Five Functions
One Dimensional Arrays
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
1 CS 161 Introduction to Programming and Problem Solving Chapter 9 C++ Program Components Herbert G. Mayer, PSU Status 10/20/2014.
1 ICS103 Programming in C Lecture 13: Arrays II. 2 Outline Review on Arrays Using array elements as function arguments  Examples Using arrays as function.
CS 201 Functions Debzani Deb.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Chapter 6: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
CS 201 Functions Debzani Deb.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Chapter 6: User-Defined Functions I
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
1 Functions. 2 Function A program segment that carries out some specific, well-defined task Example  A function to add two numbers  A function to find.
Searching an Array: Linear and Binary Search Spring 2013Programming and Data Structure1.
Sudeshna Sarkar, IIT Kharagpur 1 Functions : Recursion Lecture
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
P-1 University of Washington Computer Programming I Lecture 15: Linear & Binary Search ©2000 UW CSE.
142 F -1 Functions chapter 3 of the text int main(void) { double x,y,z; … x = cube(y/3.0); … printf(“%f cubed is %f”,x,cube(x)); … return 0; } double cube(double.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
Sudeshna Sarkar, IIT Kharagpur 1 Functions Lecture
Sorting & Searching Review. Selection Sort 1. Find the smallest element 2. Move to the front of the array (swap with front) 3. Repeat Steps 1&2, but ignoring.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Sudeshna Sarkar, IIT Kharagpur 1 Functions Lecture
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 ICS103 Programming in C Lecture 8: Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Programming Applications. Functions every C program must have a function called main program execution always begins with function main any.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Data Structures Arrays and Lists Part 2 More List Operations.
ARRAYS Lecture void reverse (int x[], int size) { int i; for (i=0; i< (size/2); i++) temp = x[size-i-1] ; x[size-1-1] = x[i] ; x[i] = temp;
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Chapter 6: User-Defined Functions I
Sorting and Searching Sudeshna Sarkar 7th Feb 2017.
CSCI 161: Introduction to Programming Function
User-Defined Functions
Looping.
ARRAYS Lecture
Functions, Part 1 of 3 Topics Using Predefined Functions
Chapter 6: User-Defined Functions I
Functions, Part 1 of 3 Topics Using Predefined Functions
Functions, Part 1 of 3 Topics Using Predefined Functions
ARRAYS ..
Presentation transcript:

Functions

A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== ======= to separate sections of output.

Solution #include int main (void) { /* produce some output */ /* print banner line */ printf(“==============\n”) ; /* produce more output */ printf(“==============\n”); /* produce even more output */ printf(“==============\n”); /* produce final output */ }

Critique Redundant code What if we want to change the display e.g. to print a blank line before and after each line with =’s ? What if we want to print banner lines in some other program?

The Solution: Functions Definition: A function is a named code sequence A function can be executed by using its name as a statement or expression. The function may have parameters - information that can be different each time the function is executed. The function may compute and return a value.

Why use functions ? Functions provide an abstraction when writing a program - allow low-level details to be packaged. Able to package a computation we need to perform at multiple spots within a program. Write once, use many times. If changes are needed, they only have to be done once, in one place.

Why use functions ? Allows the programmer to create a program from smaller, simpler sub-components. Many programs are far too large to understand all at once. Functions give us a way to break a large program into smaller pieces A function should perform a well-defined task.

Common functions main (void) {... } Function definition for main() printf (“%d + %d is %d\n”,x,y,z); scanf (“%d%d”, &x, &y) ; limit = sqrt ((double) num); Function calls

More common functions Every standard C compiler comes with a set of standard libraries. #include Tells the compiler you will use the standard IO library #include C’s standard math library functions: sqrt, pow, sin, cos, exp,... isspace,...

Defining your own functions You may define your own functions in your programs You define a function by giving its name and writing the code that is executed when the function is called.

Function definition /* print banner line */ void print_banner (void) { printf (“=========”); printf (“=========\n”); } heading comment function name function body (statements to be executed) A function can have ANY number of ANY kind of statements

/* print banner line */ void print_banner (void) { printf (“=========”); printf (“=========\n”); } void void has two different roles in this function definition. indicates that the function does not return (have) an output value. indicates that the function has no parameters.

Calling a function int main (void) { /* produce some output */... print_banner (); /* produce more output */... print_banner (); /* produce final output */... print_banner (); } To execute the function, it is called or invoked from within a program or another function. Note: A function that does not return a value can be called wherever a statement is allowed.

Terminology main () is the caller print_banner() is the callee. main() invokes / calls print_banner() 3 times. print_banner() is called from main()

Function Control Flow /* print banner line */ void print_banner (void) { printf(“************ **\n”); } int main (void) {... print_banner ();... print_banner (); return (0); } main (void) { print_banner (); print_banner (); } print_banner { } print_banner { }

Control Flow All C programs Start at main () /*no matter where main()is */ Continue in top-to-bottom order, statement by statement, unless the order is changed by: function call function return if loops

Function Type and Value A function can return a value. Like all values in C, a function return value has a type. The function has the type of its returned value. /* Get number from user */ int get_input (void) { int num; printf (“Enter a number:”); scanf (“%d”, &num); return (num); } function type return statement returned value

Calling a function A value-returning function is called by including it in an expression. int main (void) { int x, y; x = get_input() ; y = get_input() ; printf (“ %d + %d = %d\n”, x, y, x+y); return (0); } Note : A value returning function can be used anywhere an expression of the same type can be used.

return In a value-returning function (result type is not void) return does two distinct things : 1. specify the value returned by the execution of the function 2. terminate that execution of the function. In a void function: return is optional at the end of the function body. return may also be used to terminate execution of the function explicitly. No return value should appear following return.

void compute_and_print_itax () { double income; scanf (“%f”, &income); if (income < 50000){ printf (“Income tax = Nil\n”); return; } if (income < 60000){ printf (“Income tax = %f\n”, 0.1*(income-50000); return; } if (income < ) { printf (“Income tax = %f\n”, 0.2*(income-60000)+1000); return ; } printf (“Income tax = %f\n”, 0.3*(income )+19000); } Terminate function execution before reaching the end

Function parameters It is very often useful if a function can operate on different data values each time it is called. Such values are function (input) parameters. The function specifies its inputs as parameters in the function declaration. /* Find area of a circle with radius r */ double area (double r) { return ( *r*r) ; } parameter

Arguments The function call must include a matching argument for each parameter. When the function is executed, the value of the argument is substituted for the parameter. int main (void) {... double circum;... area1 = area(circum/2.0);... } double area (double r) { return (3.14*r*r); } parameter passing

Control and data flow When a function is called: (1) control transfers to the function body (2) argument values are copied (3) the function executes (4) control and return value return to the point of call.

Control and data flow int main (void) { double x, y, z; y=6.0; x = area(y/2.0);... z = area(7.88);... return (0); } double area (double r) { return (3.14*r*r); }

Style notes Put comments above a function body to specify completely what the function does, including the significance of all the parameters. /* Find area of a circle with radius r */ double area (double r) { return ( *r*r) ; }

Multiple parameters a function may have more than one parameter arguments must match parameters in number, order and type. void main () { double x, y; int z; char op;... z = operate (x, y, op);... } arguments int operate (double x, double y, char op) { switch (op) { case ‘+’ : return x+y+0.5 ; case ‘~’ : if (x>y) return x-y + 0.5; return y-x+0.5; case ‘x’ : return x*y + 0.5; default : return –1; } parameters

Rules for using functions Arguments must match parameters: in number in order in type A function can only return one value. but it might contain more than one return statement. In a function with return type T, the return expression must be of type T. A function with return type T can be used anywhere an expression of type T can be used.

Local variables A function can define its own local variables. The locals have meaning only within the function. Each execution of the function uses a new set of locals Local variables cease to exist when the function returns Parameters are also local.

Local variables /* Find the area of a circle with diameter d */ double circle_area (double d) { double radius, area; radius = d/2.0; area = 3.14*radius*radius; return (area); } parameter local variables

Defining function prototypes Functions should be declared before they are used (invoked). Instead of writing the complete function, you can use function prototypes to declare a function so that it can be used. It is a good programming style to use function prototypes.

Function prototypes int operate (double x, double y, char op) ; int operate (double, double, char); void print_average (double, int); int get_intput (void); void print_banner (void); Write a function prototype near the top of the program Can use the function anywhere thereafter.

#define TRUE 1 #define FALSE 0 /* Find if x is a factor of y */ int isFactor (int x, int y) { if (y%x == 0) return TRUE; return FALSE; } /* Rteurns true if x is a prime number */ int isPrime (int x) { int factor; for (factor=2; factor <= sqrRt(x); factor++) if (isFactor(factor, x)) return FALSE; } /* Finds all prime numbers in acertain range */ void main (void) { int i, start, limit; scanf (“%d%d”, &start,&limit); for (i=start; i<=limit; i++) { if (isPrime (i)) printf (“%d “, i); } Example :

Back to Arrays

Arrays as parameters of functions An array passed as a parameter is not copied

Array operations #define MAXS 100 int insert (int[], int, int, int) ; int delete (int[], int, int) ; int getelement (int[], int, int) ; int readarray (int[], int) ; main (){ int a[MAXS]; int size; size = readarray (a, 10) ; size = insert (a, size, 4, 7) ; x = getelement (a, size, 3) ; size = delete (a, size, 3) ; }

Array operations #define MAXS 100 int insert (int[], int, int, int) ; int delete (int[], int, int) ; int getelement (int[], int, int) ; int readarray (int[], int) ; main (){ int a[MAXS]; int size; size = readarray (a, 10) ; size = insert (a, size, 4, 7) ; x = getelement (a, size, 3) ; size = delete (a, size, 3) ; } int readarray (int x[], int size){ int i; for (i=0; i<size; i++) scanf(“%d”, &x[i]) ; return size; } int getelement (int x[], int size, int pos){ if (pos <size) return x[pos] ; return -1; } int insert (int x[], int size, int pos. int val){ for (k=size; k>pos; k--) x[k] = x[k-1] ; x[pos] = val ; return size+1; }

void reverse (int x[], int size) { } int findmax (int x[], int size) { }

void reverse (int x[], int size) { int i; for (i=0; i< (size/2); i++) temp = x[size-i-1] ; x[size-1-1] = x[i] ; x[i] = temp; } int findmax (int x[], int size) { int i, max; max = x[0]; for (i=1; i< size; i++) if (x[i] > max) max = x[i] ; return max; }

Searching an Array: Linear and Binary Search

Searching Check if a given element (key) occurs in the array. If the array is unsorted : start at the beginning of the array inspect every element to see if it matches the key

Linear Search /* If key appears in a[0..size-1], return its location, pos, s.t. a[pos] == key. If key is not found, return -1 */ int search (int a[], int size, int key){ int pos = 0; while (pos < size && a[pos] != key) pos++; if (pos<n) return pos; return -1; }

Linear Search int x= {12,-3, 78,67,6,50,19,10} ; Trace the following calls : search (x, 8,6) ; search (x,8,5) ;

Searching a sorted array Binary search works if the array is sorted Look for the target in the middle If you don’t find it, you can ignore half of the array, and repeat the process with the other half.

Binary Search Strategy What we want : Find split betwen values larger and smaller than x : <=key>key <=key?>key x: 0 n LR 0nLR Situation while searching : Step : Look at [(L+R)/2]. Move L or R to the middle depending on test.

Binary Search /* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key){ int L, R, mid; ______________________; while (_________________){ } ____________________ ; }

/* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key){ int L, R, mid; ______________________; while (_________________){ mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } ____________________ ; } Binary Search mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid;

/* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key){ int L, R, mid; ______________________; while (_________________){ mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } ____________________ ; } Binary Search: loop termination L+1 != R

/* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key){ int L, R, mid; ______________________; while ( L+1 != R){ mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } Binary Search: Return result if (L>=0 && x[L]==key) return L; else return -1;

/* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */ int binsearch (int x[], int size, int key){ int L, R, mid; ______________________; while ( L+1 != R){ mid = (L+R)/2; if (x[mid] <= key) L = mid; else R = mid; } if (L>=0 && x[L]==key) return L; else return -1; } Binary Search: Initialization L=-1; R=size;

Binary Search Examples Trace : binsearch (x, 9, 3); binsearch (x, 9, 145); binsearch (x, 9, 45);

Is it worth the trouble ? Suppose you had 1000 elements Ordinary search (if key is a member of x) would require 500 comparisons on average. Binary search after 1st compare, left with 500 elements after 2nd compare, left with 250 elements After at most 10 steps, you are done. What if you had 1 million elements ?

Sorting Given an array x[0], x[1],..., x[size-1] reorder entries so that x[0]<=x[1]<=... <=x[size-1]

Sorting Problem What we want : Data sorted in order sorted : x[0]<=x[1]<=... <=x[size-1] x: 0 size Initial conditions : unsorted x: 0 size

Selection Sort General situation : remainder, unsortedsmallest elements, sorted 0size k Step : Find smallest element, mval, in x[k..size-1] Swap smallest element with x[k], then increase k. x: smallest elements, sorted 0sizek x: mval

Subproblem : : /* Yield location of smallest element int[x] in x[0.. size-1];*/ int min_loc (int x[], int, int size) int j, pos; /* x[pos] is the smallest element found so far */ pos = k; for (j=k+1; j<size; j++) if (x[i] < x[pos]) pos = j; return pos; }

Selection Sort /* Sort x[0..size-1] in non-decreasing order */ int selsort (int x[], int size){ int k, m; for (k=0; k<size-1; k++){ m = min_loc(x, k, size); temp = a[k]; a[k] = a[m]; a[m] = temp; }

Example x: x: x: x: x: x: x:

Analysis How many steps are needed to sort n things ? Total number of steps proportional to n 2

Insertion Sort #define MAXN 100 void InsertSort (int list[MAXN], int size) ; main (){ int index, size; int numbers[MAXN]; /* Get Input */ size = readarray (numbers) ; printarray (numbers, size) ; InsertSort (numbers, size) ; printarray (numbers, size) ; }

void InsertSort (int list[], int size){ for (i=1; i<size; i++) item = list[i] ; for (j=i-1; (j>=0)&& (list[j] > i); j--) list[j+1] = list[j]; list[j+1] = item ; }

Common pitfalls with arrays in C Exceeding the array bounds int array[10]; for (i=0; i<=10; i++) array[i] = 0; C does not support array declaratiions with variable expressions. void fun (int array, int size){ int temp[size] ;... }

Local variables of main : i, start, limit Parameters of isPrime : x Local variables of isPrime : factor Parameters of isFactor : x, y

Local Variables Formal parameters and variables declared in a function are local to it. cannot be accessed or used by other functions directly Allocated (created) on function entry. De-allocated (destroyed) on function return. Formal parameters initialized by copying value of actual parameter. (“Call by value”)

Call by value void printDouble (int x) { printf (“Double of %d “, x); x *= 2; printf (“is %d\n”, x) ; } void main () { int num=15; printDouble (num); printf (“ num = %d\n”, num); } Note : The parameter of a function can be a constant, variable, expression – anything that has a value. Only the value is passed to the function.