Lecture 9 - C Functions

Similar documents
C Programming for Engineers Functions

BSM540 Basics of C Language

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

Functions. Arash Rafiey. September 26, 2017

Functions. Systems Programming Concepts

Chapter 7 Functions. Now consider a more advanced example:

Programming for Engineers Functions

C Functions. 5.2 Program Modules in C

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

ECET 264 C Programming Language with Applications. C Program Control

Lecture 04 FUNCTIONS AND ARRAYS

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?

Language comparison. C has pointers. Java has references. C++ has pointers and references

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

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Introduction to Programming (Java) 4/12

Unit 7. Functions. Need of User Defined Functions

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

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

Chapter 4 Functions By C.K. Liang

Lecture 04 FUNCTIONS AND ARRAYS

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

CSCI 2132 Software Development. Lecture 17: Functions and Recursion

User Defined Functions

Personal SE. Functions, Arrays, Strings & Command Line Arguments

A PROBLEM can be solved easily if it is decomposed into parts. Similarly a C program decomposes a program into its component functions.

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

CS240: Programming in C

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

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

UNIT III (PART-II) & UNIT IV(PART-I)

Procedural programming with C

Arrays and Pointers. CSE 2031 Fall November 11, 2013

CS1150 Principles of Computer Science Methods

MODULE 3: Arrays, Functions and Strings

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265

Fundamentals of Programming & Procedural Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

BSM540 Basics of C Language

/* EXAMPLE 1 */ #include<stdio.h> int main() { float i=10, *j; void *k; k=&i; j=k; printf("%f\n", *j);

Functions BCA-105. Few Facts About Functions:

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

CS240: Programming in C

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

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

CSCI 2132 Software Development. Lecture 18: Functions

ECET 264 C Programming Language with Applications

Arrays and Pointers (part 1)

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

AMCAT Automata Coding Sample Questions And Answers

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

PROGRAMMAZIONE I A.A. 2017/2018

CHAPTER 4 FUNCTIONS. 4.1 Introduction

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

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

Chapter 5 C Functions

Computer Programming

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

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

M.CS201 Programming language

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Engineering program development 6. Edited by Péter Vass

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

Chapter 8: Function. In this chapter, you will learn about

EECS402 Lecture 02. Functions. Function Prototype

M.CS201 Programming language

Lecture 2: C Programming Basic

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

Programming. Functions and File I/O

EC 413 Computer Organization

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 12, FALL 2012

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

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

CS1150 Principles of Computer Science Methods

C Programming Language

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

Lecture 5: Methods CS2301

Fundamentals of Computer Programming Using C

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Arrays and Pointers (part 1)

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Binding and Variables

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

Programming and Data Structures

CS101 Introduction to computing Function, Scope Rules and Storage class

Computers in Engineering. Moving From Fortran to C Part 2 Michael A. Hawker

Computer Science & Engineering 150A Problem Solving Using Computers

CS111: PROGRAMMING LANGUAGE II

ECET 264 C Programming Language with Applications

& Technology. G) Functions. void. Argument2, Example: (Argument1, Syllabus for 1. 1 What. has a unique. 2) Function name. passed to.

Computers in Engineering COMP 208. Roots of a Quadratic in C 10/25/2007. Moving From Fortran to C Part 2 Michael A. Hawker

Engineering program development 7. Edited by Péter Vass

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Transcription:

ECET 264 C Programming Language with Applications Lecture 9 C Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 9- Prof. Paul I. Lin 1 Lecture 9 - C Functions C Functions Function Prototypes Function Definitions Function Calls by Value Function Calls by Reference Examples Example 9-1: Square Function Example 9-2: String Length Function Example 9-3: Function cube() Example 9-4: Max Function Example 9-5: Add1() Function Example 9-6: Averaging Elements in an Array Example 9-7: Call By Reference Swap() Example 9-8: Testing Functions Summary Lecture 15 - Prof. Paul I. Lin 2 1

C Functions Every C program must include a function called main() that begins the execution of the program. Functions allow programmers to modularize a program Function Prototypes C Functions must be declared before they are used A C function normally requires a definition of function prototype that consists of the following elements: Output parameter (Return type), function name, input parameters enclosed by a pair of parenthesis A function prototype offers a view of how to use the desired function, passing input arguments, receive a return value with known type. Lecture 15 - Prof. Paul I. Lin 3 Function Prototypes C Functions (Continue) All function prototypes are save in their specific header files with.h as extension Header files for C s standard library function can be included in a user program using the following syntax #include <stdio.h> #include <math.h> For example, as discussed earlier, the stdio.h is a header file which contains all standard I/O function definitions. The function prototypes including printf(), scanf(), etc., are save on this header file Lecture 15 - Prof. Paul I. Lin 4 2

C Functions (continue) Function Body A C function normally includes the following elements: An output parameter (Return type) Function name Input parameters enclosed by a pair of parenthesis, begin brace, local variable definitions, statements, and a return with the type that matches the Return type, and end brace. The input and output parameters provide the means for passing information in and out of a function Function s parameters are also treated as local variables of that function All variables defined in function definitions are considered local variables Lecture 15 - Prof. Paul I. Lin 5 C Functions (continue) Functions support structured programming and offer the following advantages Hierarchical flow control Break large tasks into smaller ones Easy to maintain Improve software reusability Main() Worker1 Worker2 Worker3 Worker4 Worker5 Lecture 15 - Prof. Paul I. Lin 6 3

C Functions (continue) Categories of C functions Standard library functions User defined functions Developed in house Purchased from other companies Windows API functions GUI-based Event-driven Lecture 15 - Prof. Paul I. Lin 7 Function Prototypes Important features of function prototypes: A function prototype tells the C compiler the type of data to be returned by the function the number of parameters the function expects to receive the types of the parameters the order in which these parameters are expected. Lecture 15 - Prof. Paul I. Lin 8 4

Function Prototypes (continue) The compiler uses function prototypes to validate function calls Detect syntax error - when a function call does not match the function prototype Coercion of arguments Force invalid arguments type become an appropriate type Providing documentation of functions to programmers and readers Lecture 15 - Prof. Paul I. Lin 9 Defining Functions type function_name (formal parameters) /* variable declarations */ type val; statements; return (val); Return type of function: Out Parameters or Return a value with specified data type Only one value can be returned When there is a need to get more than one value returned, use call by reference A function that does not return anything should have a type "void" Lecture 15 - Prof. Paul I. Lin 10 5

Defining Functions (cont.) Defining functions or Function prototyping type function_name (formal parameters) Return value type int square(int y); Argument name Function name Parameter type Function_name Function s name formal parameters For receiving information(arguments) Lecture 15 - Prof. Paul I. Lin 11 Function Call Functions can be called by any other functions, but can not be nested with other functions. Functions are invoked by a function call, all variables and parameters defined in function definitions are local variables of that function The parameters provide the means for communicating information between functions Lecture 15 - Prof. Paul I. Lin 12 6

Function Call (Invocation) f_name (parameters); /* if no return value is expected */ n = f_name(parameters); /* return a value */ Function call s execution sequence: Save the return address Pass arguments (through the stack) and transfer control to the function Function return a value or simply return the control to the caller Lecture 15 - Prof. Paul I. Lin 13 Example 9-1: Square Function #include <stdio.h> int square(int y) /* function prototype */ int main() int x; for (x=1; x <= 10; x++) printf( %d, square(x)); printf( \n ); return 0; call square function return Return value type void square(int y) printf( %f, square(x) Argument type /*function square definition */ int square(int y); int square(int y) Function name Parameter name return y * y; Lecture 15 - Prof. Paul I. Lin 14 7

Example 9 2: strlen() Function Problem Statement: Write a C function that examines and returns the length of a given string or character array. Analysis Return type integer is sufficient since most strings have limited length Function name strlen, a meaningful name Input parameter char s[] a character array, with s[], or any meaningful name such as string[] Lecture 15 - Prof. Paul I. Lin 15 Example 9 2: strlen() Function (cont.) Solution and Function Documentation /* Function name: strlen() * Input: a character array of any length * Returned: an integer containing the length of the array * / int strlen(char s[]) /*function definition */ int n = 0; while (s[ n++]!= '\0'); return n; Lecture 15 - Prof. Paul I. Lin 16 8

Example 9 2: strlen() Function (cont.) How to invoke the strlen() function Assume that a function named strlen() for checking the length of any arbitrary string of any length is available for use. It s function prototypes is int strlen (char s[ ]); The function body of the strlen() is as shown below: int strlen(char s[ ]) int n = 0; while (s [n++]!= '\0'); return n; Lecture 15 - Prof. Paul I. Lin 17 Example 9 2: strlen() Function (cont.) Example: How to invoke the strlen() function /* strlen_test.c */ #include <stdio.h> int strlen (char s[ ]); void main() int strlen(char s[ ]) int len; char string [80]; int n = 0; gets (string); while (s [n++]!= \0 ); len = strlen (string); return n; Lecture 15 - Prof. Paul I. Lin 18 9

Example 9 2: strlen() Function (cont.) /* test_strlen.c */ #include <stdio.h> int strlen(char s[]); /* list function prototypes */ void main() int len; char string[80]; while(1) puts("enter a string, Ctrl-C to Exit"); gets(string); len = strlen(string); printf("the length of string[%s] is %d.\n", string, len); /* Function name: strlen() * Input: a character array of * any length. * Returned: an integer * containing the length of the * array */ int strlen(char s[]) /*function definition */ int len = 0; while (s[len++]!= '\0'); return len; Lecture 15 - Prof. Paul I. Lin 19 Example 9 2: strlen() Function (cont.) OUTPUT: Enter a string, Ctrl-C to Exit C program The length of string[c program] is 10. Enter a string, Ctrl-C to Exit ECET264 The length of string[ecet264] is 8. Enter a string, Ctrl-C to Exit 1 The length of string[1] is 2. Enter a string, Ctrl-C to Exit The length of string[] is 1. Enter a string, Ctrl-C to Exit Lecture 15 - Prof. Paul I. Lin 20 10

Example 9-3: Function cube() A math function cube() compute x^3: Function Prototype saved in a specific header file along with other related function prototypes. float cube(float x); /* saved in xyz_meth.h */ Function body saved in a specific C file, xyz_math.c along with other related C functions float cube(float x) /* saved in xyz_math.c */ return (x*x*x); Lecture 15 - Prof. Paul I. Lin 21 Example 9-3: Testing Cube( ) Function (cont.) Problem Statement: You are asked to test the cube( ) function to meet the requirements of software quality. Analysis: The two system defined functions: scanf( ) and printf( ) will be needed to ask user inputs for testing, and display the testing results. Knowing that all system library functions are precompiled into the object file, therefore no source file will be needed. The IDE will link the specified system library functions during the building phase of the executable program. Lecture 15 - Prof. Paul I. Lin 22 11

Example 9-3: Testing Cube( ) Function (cont.) Analysis: We need to obtain a copy of the function prototype, and put the line as shown in xyz_math.h which may contain other math related function prototypes. float cube(float x); /* saved in xyz_meth.h */ We also need to have the source code and place it in xyz_math.c along with other math functions float cube(float x) /* saved in xyz_math.c */ return (x*x*x); Lecture 15 - Prof. Paul I. Lin 23 Example 9-3: Testing Cube( ) Function (cont.) /* cube_test.c */ #include <stdio.h> #include "xyz_math.h" void main() float n, result; while(1) printf("\nplease enter a number for computing n^3 or Crtl C to exit: "); scanf("%f", &n); result = cube(n); /* Function Call */ printf("%f^3 = %f\n", n, result); return; #include "xyz_math.c" Lecture 15 - Prof. Paul I. Lin 24 12

Example 9-3: Testing Cube( ) Function (cont.) OUTPUT: Please enter a number for computing n^3 or Crtl C to exit: 10 10.000000^3 = 1000.000000 Please enter a number for computing n^3 or Crtl C to exit: 1.0 1.000000^3 = 1.000000 Please enter a number for computing n^3 or Crtl C to exit: 0.01 0.010000^3 = 0.000001 Please enter a number for computing n^3 or Crtl C to exit: 0.001 0.001000^3 = 0.000000 Please enter a number for computing n^3 or Crtl C to exit: Lecture 15 - Prof. Paul I. Lin 25 Example 9-3: Testing Cube( ) Function (cont.) /* cube_test.c */ #include <stdio.h> #include "xyz_math.h" void main() float n, result; while(1) printf("\nplease enter a number for computing n^3 or Crtl C to exit: "); scanf("%f", &n); result = cube(n); /* Function Call */ printf("%f^3 = %f\n", n, result); printf("%e^3 = %e\n", n, result); /* %e for higher accuracy */ return; #include "xyz_math.c" Lecture 15 - Prof. Paul I. Lin 26 13

Example 9-3: Testing Cube( ) Function (cont.) NEW OUTPUT SCREEN Please enter a number for computing n^3 or Crtl C to exit: 0.0001 0.000100^3 = 0.000000 0.000100^3 = 9.999999e-013 Please enter a number for computing n^3 or Crtl C to exit: 0.00001 0.000010^3 = 0.000000 0.000010^3 = 9.999999e-016 Please enter a number for computing n^3 or Crtl C to exit: Lecture 15 - Prof. Paul I. Lin 27 Example 9-4: max() Function /* Function Prototypes */ unsigned long fac(int); int max(int a, int b);.. void main(void) int x, y, z; x = 10; y = 100; z = 1000; z = max(1, 2); /* Function call */ x = max(y, z); /* Function Bodies */ int max (int a, int b) return ((a > b)? a: b;) Lecture 15 - Prof. Paul I. Lin 28 14

Example 9 5: Add1 Function Example: A routine may use the formal arguments as temporary local variables. The variable "number" in the add1() function is also used a local variable. int add1(int number); void main(void) int add1(int number) int i = 5; int out_number; int j; out_number = number + 1;. return (out_number);. j = add1(i); /* after this i is still holds 5*/. Lecture 15 - Prof. Paul I. Lin 29 Example 9-6: Averaging Elements in an Array Problem Statement: Write a function that computes the average temperature of a temperature array. This is a floatingpoint number array which holds temperature obtained from a temperature sensor. Analysis Return type float or double Function name sumtemparray Input parameters float temp[] array, and the variable size of int type for the array elements Lecture 15 - Prof. Paul I. Lin 30 15

Example 9-6: Averaging Elements in an Array (cont.) Solution: float avgtemparray (float temp[], int size) int i = 0; float sum = 0.0; while (i < size) sum += temp[i]; i++; return (sum/size); Lecture 15 - Prof. Paul I. Lin 31 Example 9-6: Averaging Elements in an Array (cont.) /* sumarray.c */ #include <stdio.h> float avgtemparray(float temp[], int size); void main() float tempsum; int len; float tempsensor[10] = 67.3, 68.0, 68.2, 68.5, 68.4, 69.0, 65.0, 72.0, 69.2, 65.3; len = sizeof(tempsensor)/sizeof(float); printf("number of elements in the array tempsensor[] is %d.\n", len); tempavg = avgtemparray(tempsensor, len); printf("the average temperature is %5.2f degree F.\n", tempavg); float avgtemparray (float temp[], int size) int i = 0; float sum = 0.0; while (i < size) sum += temp[i]; i++; return (sum/size); Lecture 15 - Prof. Paul I. Lin 32 16

Example 9-6: Averaging Elements in an Array (cont.) Output: Number of elements in the array tempsensor[] is 10. The average temperature is 68.00 degree F. Press any key to continue Lecture 15 - Prof. Paul I. Lin 33 Call By Value and By Reference Call By Value Most C functions are written as call-byvalue functions When arguments are passed by value, a copy of the argument s value is made and passed to the called function. The original value can not be changed Only one value can be returned Lecture 15 - Prof. Paul I. Lin 34 17

Call By Value and By Reference (continue) Call By Reference Reference refers to a memory address of the argument The operator & or pointer are normally used for passing address(es) It allows the access of a block of data When an argument is passed by reference, the caller actually allows the called function to modify the original variable s value. Lecture 15 - Prof. Paul I. Lin 35 Call By Value and By Reference (cont.) Call By Reference in C is accomplished by the following necessary steps: 1. Declare function parameter(s) as pointer(s) types. 2. Use the dereferenced pointer in the function body to access the values of variables. 3. Pass addresses as arguments when the function is called. Lecture 15 - Prof. Paul I. Lin 36 18

Example 9 7: A Call-By-Reference swap() Function Example: call by reference. The function swap() accepts two pointers and physically exchange the values of variables x and y. #include <stdio.h> void swap(int *x, int *y) void swap(int *x, int *y); void main(void) int temp; /* get the value at address x */ int x, y; temp = *x; x = 10; *x = *y; y = 20; *y = temp; printf("x = %d, y = %d\n", x, y); printf("&x = %d, &y = %d\n", &x, &y); swap(&x,&y); /* call the function swap() */ printf("x = %d, y = %d\n", x, y); printf("&x = %d, &y = %d\n", &x, &y); Lecture 15 - Prof. Paul I. Lin 37 Example 9-8: Testing Functions Problem statement: You are given a func1.c file which contains three functions: int min(int a, int b); int max(int a, int b); double power(float x, int n); And you are asked to test and document the functions and testing results. Analysis: We arrange the functions and the main in the order as listed: - Function prototypes - Main drivers and testing data setup - Function bodies at the end Lecture 15 - Prof. Paul I. Lin 38 19

Example 9-8: Testing Functions /* func1_test.c */ #include <stdio.h> int min(int a, int b); int max(int a, int b); double power(float x, int n); /* driver for testing functions */ void main() int x, y, z; double p, w; x = 10; y = 20; z = min(x, y);printf("min = %d\n", z); z = max(x, y);printf("max = %d\n", z); Lecture 15 - Prof. Paul I. Lin 39 Example 9-8: Testing Functions (cont.) w = 0; p = power(w, 3);printf("power(0,3) = %lf\n", p); w = -0.1; p = power(w, 3);printf("power(-0.1,3) = %lf\n", p); w = 0.1; p = power(w, 3);printf("power(0.1,3) = %lf\n", p); #include func1.c Lecture 15 - Prof. Paul I. Lin 40 20

Example 9-8: Testing Functions (cont.) /* func1.c - A file consists of functions */ int min(int a, int b) int z; if(a < b) z = a; else z = b; return z; int max(int a, int b) int x; x = (a > b)? a: b; return x; double power(float x, int n) double y = 1.0; if(n == 0) return 1.0; if(n < 0) x = 1.0/x; n = -n; while(n-- > 0) y *= x; return y; Lecture 15 - Prof. Paul I. Lin 41 Example 9-8: Testing Function (cont.) Output: min = 10 max = 20 power(0.0,3) = 0.000000 power(-0.1,3) = -0.001000 power(0.1,3) = 0.00100 Lecture 15 - Prof. Paul I. Lin 42 21

Summary C Functions Function Prototypes Function Definitions Function Calls by Value and by Reference 8 Example Programs Next Standard Mathematics Functions <math.h> More examples using <math.h> Standard Utility Functions <stdlib.h> Lecture 15 - Prof. Paul I. Lin 43 Question? Answers lin@ipfw.edu Lecture 15 - Prof. Paul I. Lin 44 22