9. FUNCTIONS.

Slides:



Advertisements
Similar presentations
Chapter 6: User-Defined Functions I
Advertisements

C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Chapter 6: User-Defined Functions I
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
C programming---Arrays scalar: capable of holding a single data item aggregate variables: capable of holding a collections of values. Two kinds of aggregates.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
16&17-2 Grasp the concept of top-down programming Identify Function Headers and Prototypes Understand when and where prototypes used Understand how arguments.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 11: Pointers Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 11 Pointers.
Learners Support Publications Functions in C++
CSCI 171 Presentation 8 Built-in Functions, Preprocessor Directives, and Macros.
COP 3275: Chapter 09 Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Gator Engineering One-dimensional array Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Sorting –Bubble sort –Merge sort –Quick sort –Selection.
Chapter 3: User-Defined Functions I
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter 9: Functions Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
Chapter 9: Functions Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
6. LOOPS. Example: Summing a Series of Numbers #include int main(void) { int n, sum = 0; printf("This program sums a series of numbers.\n"); printf("Enter.
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
Chapter 12: Pointers and Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
Objectives: How to define and call functions. Function declarations and how they differ from function definitions. How arguments are passed to functions.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Advanced Programming in C Passing Parameter to Function.
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
User-Written Functions
Chapter 6 - Functions modular programming general function format
Chapter 6: User-Defined Functions I
C programming---Arrays
Functions Chapter 5 CS12 - Computer Programming 1 Chapter 5.
Functions and Structured Programming
Functions Dr. Sajib Datta
Loops Chapter 6 Copyright © 2008 W. W. Norton & Company.
Programmazione I a.a. 2017/2018.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Lecture 6 C++ Programming
Functions.
User-Defined Functions
Pointers and Arrays Chapter 12
Lecture [7][0] Functions
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company. 1
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company.
6.12 Default Arguments.
6 Chapter Functions.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company.
Pointers and Arrays Chapter 12
Pointers (continued) Chapter 11
Pointers and Arrays Chapter 12
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company.
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
A First Book of ANSI C Fourth Edition
Chapter 6: User-Defined Functions I
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Department of Statistics St. Joseph’s College (Autonomous)
Functions Chapter 9 Copyright © 2008 W. W. Norton & Company.
Instructor: Hidayah Elias Course: COMPUTER PROGRAMMING (BFC 2042)
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
Presentation transcript:

9. FUNCTIONS

Example: Printing a Message /* Illustrates functions with no arguments */ #include <stdio.h> void print_pun(void) { printf("To C, or not to C: "); printf("that is the question.\n"); } int main(void) print_pun(); return 0;

Example: Counting Down /* Illustrates functions with arguments */ #include <stdio.h> void print_count(int n) { printf("T minus %d and counting\n", n); } int main(void) int i; for (i = 10; i > 0; --i) print_count(i); return 0;

Example: Finding the Larger of Two Numbers /* Illustrates functions that return a value */ #include <stdio.h> int max(int a, int b) { if (a > b) return a; else return b; } int main(void) int i, j; printf("Enter two numbers: "); scanf("%d%d", &i, &j); printf("The larger number is %d\n", max(i, j)); return 0;

Defining a Function • A function definition has the following appearance: result-type function-name ( parameters ) { declarations statements } • If a function does not return a value, its result type should be specified to be void. • If the result type is omitted, the function is assumed to return a value of type int. • If a function has no parameters, the word void should appear between the parentheses.

Calling a Function • To call a function, give the function name followed by a list of arguments (in parentheses). • A call of a void function must be a statement: print_pun(); print_count(i); • A call of a non-void function returns a value that can be stored in a variable, tested, printed, or used in some other way: k = max(i, j); if (max(i, j) > 10) ... printf("The larger number is %d\n", max(i, j));

Calling a Function • The value returned by a non-void function can always be discarded if desired: max(i, j); /* return value is discarded */ To make it clear that the return value is deliberately being discarded, it is possible to put (void) before the call: (void) max(i, j); /* return value is discarded */ • Warning: A call of a function with no arguments must include a pair of empty parentheses. Without the parentheses, the function is not called: f; /* wrong; f is not called */

Arguments • All arguments are passed by value. In other words, changing the value of a parameter affects only the function’s local copy. void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } ... swap(x, y); /* the values of x and y are not changed */

Arguments • If the type of an argument doesn’t match the type of the matching parameter, the argument will be converted to the proper type automatically: #include <stdio.h> float square(float x) { return x * x; } int main(void) int i; i = 5; printf("The answer is %g\n", square(i)); return 0;

Arguments • Warning: Automatic conversion of arguments takes place only if the compiler has previously seen a definition of the function.

Array Arguments • When a parameter is a one-dimensional array, the length of the array need not be specified: int find_largest(int a[], int n) { int i, max; max = a[0]; for (i = 1; i < n; i++) if (a[i] > max) max = a[i]; return max; }

Array Arguments • find_largest is called in the following way: #define N 100 int i, b[N]; i = find_largest(b, N); Array arguments are passed by reference: a copy of the array argument is not made Functions cannot return arrays

Array arguments If a parameter is a multidimensional array, only the length of the first dimension may be omitted. #define LEN 10   int sum_two_dimensional_array(int a[][LEN], int n) { int i, j, sum = 0; for (i = 0; i < n; i++) for (j = 0; j < LEN; j++) sum += a[i][j]; return sum; }

return Statement • The return statement in a non-void function has the form return expression ; The expression is often just a constant or variable, but may be more complicated. • Executing a return statement has two effects: The function immediately returns to where it was called. The value of the specified expression is returned as the value of the function. • If the type of the expression doesn’t match the function’s return type, the expression will be implicitly converted to the return type.

return Statement • A function may contain more than one return statement: int max(int a, int b) { if (a > b) return a; else return b; }

Returning from main • main is a function like any other. Its return type, by default, is int. • The value returned by main is a status code that can be tested when the program terminates. This feature is useful in batch files and shell scripts. • By convention, main returns 0 if the program terminates normally. To indicate abnormal termination, main returns a value other than 0 (typically 1).

The exit Function • Another way to terminate a program is to call the exit function. The argument to exit should be either EXIT_SUCCESS or EXIT_FAILURE: exit(EXIT_SUCCESS); /* normal termination */ exit(EXIT_FAILURE); /* abnormal termination */ Calling exit with 0 as the argument has the same effect as calling exit with EXIT_SUCCESS as the argument.

The exit Function • Inside main, the call is equivalent to exit(expression); is equivalent to return expression; The difference between exit and return is that exit can be called from any function, not just from main. • Note: Programs that use exit should contain the following line: #include <stdlib.h>

Function declaration Header Prototype Signature

Function declaration #include <stdio.h>   double average(double a, double b); /* DECLARATION */ int main(void) { double x, y, z; printf("Enter three numbers: "); scanf("%lf%lf%lf", &x, &y, &z); printf("Average of %g and %g: %g\n", x, y, average(x, y)); printf("Average of %g and %g: %g\n", y, z, average(y, z)); printf("Average of %g and %g: %g\n", x, z, average(x, z)); return 0; } double average(double a, double b) /* DEFINITION */ return (a + b) / 2;

Use functions A program can be divided into small pieces that are easier to understand and modify. We can avoid duplicating code that’s used more than once. A function that was originally part of one program can be reused in other programs

Recursion A function is recursive if it calls itself. Examples:

Quicksort Divide and conquer Quicksort algorithm 1. Choose an array element e (the “partitioning element”), then rearrange the array so that elements 1, …, i – 1 are less than or equal to e, element i contains e, and elements i + 1, …, n are greater than or equal to e. 2. Sort elements 1, …, i – 1 by using Quicksort recursively. 3. Sort elements i + 1, …, n by using Quicksort recursively.

/* Sorts an array of integers using Quicksort algorithm */   #include <stdio.h> #define N 10 void quicksort(int a[], int low, int high); int split(int a[], int low, int high); int main(void) { int a[N], i; printf("Enter %d numbers to be sorted: ", N); for (i = 0; i < N; i++) scanf("%d", &a[i]); quicksort(a, 0, N - 1); printf("In sorted order: "); printf("%d ", a[i]); printf("\n"); return 0; }

void quicksort(int a[], int low, int high) { int middle;   if (low >= high) return; middle = split(a, low, high); quicksort(a, low, middle - 1); quicksort(a, middle + 1, high); }

int split(int a[], int low, int high) { int part_element = a[low]; int part_low[N],part_high[N], n_low = 0, n_high = 0, i; for (i = low+1; i <= high; i++) if (a[i] <= part_element) part_low[n_low++]=a[i]; else part_high[n_high++]=a[i]; for (i = 0; i < n_low; i++) a[i+low] = part_low[i]; a[i+low]=part_element; for (i = 0; i < n_high; i++) a[i+low+n_low+1] = part_high[i]; return low+n_low; }