Chapter 4 Function By C. Shing ITEC Dept Radford University.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Modular Programming With Functions
C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7: User-Defined Functions II
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Overview creating your own functions calling your own functions.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
1 Chapter 9 Scope, Lifetime, and More on Functions.
By Sidhant Garg.  C was developed between by Dennis Ritchie at Bell Laboratories for use with the Unix Operating System.  Unlike previously.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Functions Why we use functions C library functions Creating our own functions.
CMSC 1041 Functions II Functions that return a value.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
Chapter 3 Flow Control By C. Shing ITEC Dept Radford University.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Introduction As programmers, we don’t want to have to implement functions for every possible task we encounter. The Standard C library contains functions.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Sudeshna Sarkar, IIT Kharagpur 1 I/O in C + Misc Lecture –
CHAPTER 8 Scope, Lifetime, and More on Functions.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
Functions Course conducted by: Md.Raihan ul Masood
C Characters and Strings
C Functions Pepper.
Functions, Part 2 of 2 Topics Functions That Return a Value
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
C Short Overview Lembit Jürimägi.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Deitel- C:How to Program (5ed)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 9 Scope, Lifetime, and More on Functions
Chapter 6 - Functions Outline 5.1 Introduction
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
A First Book of ANSI C Fourth Edition
By C. Shing ITEC Dept Radford University
Programming Languages and Paradigms
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
C Characters and Strings
Assignment Operators Topics Increment and Decrement Operators
Presentation transcript:

Chapter 4 Function By C. Shing ITEC Dept Radford University

Slide 2 Objectives Understand how to use library functions Know how to write user functions Understand the scope rule Understand pass by value Understand how variables and functions are stored

Slide 3 Functions Library functions: any function,that returns int, must return -1 (EOF) if not successful e.g. scanf(“%c”, &character) returns -1 if reach end of file Question: Read in characters until the end of file and check whether it is a newline character. Which one is correct? (1) while(scanf(“%c”, &character) == ‘\n’) (2) while(scanf(“%c”, &character) >0 && character == ‘\n’) Another way to write it is while(scanf(“%c”, &character) != EOF && character == ‘\n’) User-defined functions

Slide 4 Library Functions Defined in stdio.h printf(): format output getchar(): macro to read a character from keyboard, buffered putchar(): macro to print a character to screen, buffered Example: readchar.creadchar.c

Slide 5 Library Functions (Cont.) Defined in stdlib.h rand(): random number between 0 and RAND_MAX srand(seed): starts from random seed

Slide 6 Library Functions (Cont.) Defined in stdlib.h (Cont.) atoi (string_var): convert string variable and return an intege atof (string_var): convert string variable and return a float atol(string_var): convert string variable and return a long int strtod(string_var, endstring): convert string variable and return a double and stores the rest non-double in endstring strtol(string_var, endstring,0): convert string variable and return a long int and stores the rest non-long int in endstring strtoul(string_var, endstring,0): convert string variable and return an unsigned long and stores the rest non-long int in endstring

Slide 7 Library Functions (Cont.) Example. atoi (“10”) returns 10 or int j; char c; scanf(“%c”, &c); // type in 9 j=atoi(&c); // j also contains 9 or j= c – ‘0’; // character stored as ASCII code

Slide 8 Library Functions (Cont.) Defined in assert.h assert(condition): macro to check whether condition is true if false, print error message limits.h UINT_MAX: unsigned int max INT_MAX: int max Example: limit.climit.c

Slide 9 Library Functions (Cont.) Defined in ctype.h isspace(character): macro to check whether character is a white space(‘\t’, ’\n’, ‘ ‘, ‘\r’, ‘\f’, ‘\v’) isupper(character): macro to check whether character is an upper case isdigit(character): return 1 if character is a digit isalpha(character): returns 1 if character is a letter isalnum(character): returns 1 if character is either a digit or a letter tolower(character): change character to lower case iscntrl (character): returns 1 if it is a control character

Slide 10 Library Functions (Cont.) Defined in (Cont.) math.h sin(), cos(), tan(), sqrt(), pow(), exp(), log() fabs(): absolute value of a float ceil(): smallest integer upper bound floor(): greatest integer lower bound pow(x, y): x raised to power y fmod(x,y): remainder of x/y as float

Slide 11 Library Functions (Cont.) time.h time(NULL): number of seconds since Jan 1, 1970 Example: dice.cdice.c

Slide 12 User Defined Function Need function prototype (function header) Return_type function_name (formal parameter_types); Declare before function definition, (i.e. header and body) put after #include lines and before main function

Slide 13 User Defined Function (Cont.) Function definition Header: Return_type function_name (formal parameter list) Body or block: { //declaration_of_variables_not_in_formal_parameter_list … // function call // returned function value is stored under function name variable=called_function_name (actual parameters); … // needed if any expression to be returned return expression; }

Slide 14 Example: Skip blank Skip any character

Slide 15 Scope Rule The variable is meaningful and unique in its defined block The local variable redefined scope precedes the global variable if use the same name Example: scope.cscope.c

Slide 16 Scope Rule (Cont.) Answer: Before 1st nested block: x= 1, y= 2, z=3 1st nested block: x= 4, y= 5, z=6 After 1st nested block: x= 1, y= 2, z=3 Nest in 2nd nested block: x= 8, y= 7, z=8 2nd nested block: x= 8, y= 7, z=7 After 2nd nested block: x= 8, y= 2, z=7 Can you try this one? scope2.cscope2.c

Slide 17 Pass By Value A copy of function actual parameters are passed to formal parameters in the called function according to parameter positions Example: byVal.cbyVal.c

Slide 18 Storage Class Represent how to store variables and functions in program Global variable: permanent storage Local variable: temporary storage 4 classes auto Static: used in the same file register Extern: used in different file

Slide 19 Storage Class - auto Local variable: allocate memory when declared, destroy when exit the scope of the variable Default when declare a variable Store in stack space Example: int i; // same as //auto int i;

Slide 20 Storage Class - static Retain value when exit the scope of the variable (permanent storage) Automatically initialized once when declared Used as a global variable and a default Visible in the same file only Declare as static type variable[=initial value]; The initial value only initialize the variable once when called

Slide 21 Storage Class – static (Cont.) 1. Within a function Example: dice_static.cdice_static.c

Slide 22 Storage Class – static (Cont.) 2. Between functions within the same file: global to functions after variable declaration, Example: dice_static_global.cdice_static_global.c

Slide 23 Example Note: the static storage class must occur in the same file Count # of skipped blanks

Slide 24 Storage Class - register Declare and use positions must be as close as possible Use fast register to store loop control variable if available to improve execution speed If no register is available, use auto class for the variable Example: dice_register.cdice_register.c

Slide 25 Storage Class - extern The external variable defined are global from the point of declaration Automatically initialized when declared Visible in different files Declared as extern type variable; Example: dice.extern1.c, dice_extern2.cdice.extern1.cdice_extern2.c

Slide 26 Example Note: the static storage class must occur in the same file Count # of skipped blanks: use 2 separate files Example 1: count1.c, count2.ccount1.ccount2.c Example 2: countskipblank1.c, countskipblank2.ccountskipblank1.ccountskipblank2.c

Slide 27 Side Effect Every variable used in a function must be defined either in formal parameters or locally Example: side.cside.c

Slide 28 Recursion C supports recursion Example: recursion.crecursion.c

Slide 29 Programming Process Requirements: what is wanted Specification: program description (iterative process) Program Design: algorithm, module definition, file format, data structure Coding Testing: write test plan, test Debugging Release Maintenance: fix bugs Revision and Updating

Slide 30 Program Design Top-Down Design: (Most Common) treat the whole problem as a big problem (main function), then use step-wise refinement to divide the problem into smaller problems (smaller functions) until the smaller problems become simple enough to be solved (use function with one task). The structure design is a tree.

Slide 31 Program Design Bottom-Up Design: starts from the bottom of the design tree (the smallest function) and work up the tree until to the root.

Slide 32 Top-Down Design Example Example: write a program to convert a series of Fahrenheit degrees into Celsius degree (use sentinel -1 to stop) The Output will look like FahrenheitCelsius _______________ FahrenheitCelsius _______________

Slide 33 Top-Down Design Example (Cont.) First, write a structure chart (design tree): usually divide the problem into 3 parts in the next level: InputData ProcessData OutputResult

Slide 34 Top-Down Design Example (Cont.) Problem (1 st level) InputData (2 nd level) ProcessData (2nd level) OutputResult (2nd level)

Slide 35 Top-Down Design Example (Cont.) We can divide OutputResult into 2 parts: PrintHeading DisplayResult

Slide 36 Top-Down Design Example (Cont.) PrintResult (2nd level) PrintHeader (3 rd level) DisplayResult (3rd level)

Slide 37 Top-Down Design Example (Cont.) Functions: 1 st level: main(void) 2 nd level: InputData: this function reads data from keyboard and outputs fahrenheit degree precondition: nothing postcondition: returns fahrenheit (double) ProcessData: this function converts the fahrenheit to celsius degree precondition: inputs fahrenheit (double) from caller postcondition: stores celsius (double) PrintResult: this function prints out fahrenheit and celsius degrees in screen precondition: inputs fahrenheit (double), celsius (double) from caller postcondition: no effects on farenheit or celsius degrees

Slide 38 Top-Down Design Example (Cont.) Functions: (Cont.) 3rd level: PrintHeader: this function prints header and __ in screen precondition: nothing postcondition: nothing DisplayResult: this function displays fahrenheit and celsius in screen precondition: fahrenheit (double), celsius (double) postcondition : nothing

Slide 39 Top-Down Design Example (Cont.) The program will look like this: #include #include // for using exit // list function prototypes double inputData (void); double ProcessData (double fahrenheit); void OutputResult (double fahrenheit, double celsius); void PrintHeader (void); void DisplayResult (double fahrenheit, double celsius);

Slide 40 Top-Down Design Example (Cont.) The program (Cont.): int main (void) { const int SENTINEL=-1; double fahrenheit, celsius; while ((fahrenheit = InputData ()) != SENTINEL) { celsius = ProcessData (fahrenheit); OutputResult (fahrenheit, celsius); } return 0; }

Slide 41 Top-Down Design Example (Cont.) The program (Cont.): double InputData (void) { double fahrenheit; if (scanf(“%lf”, &fahrenheit) != EOF) return fehrenheit; else exit(-1); } double ProcessData (double fahrenheit) { const double FACTOR=5.0/9.0; return FACTOR*(fahrenheit-32); } void OutputResult (double fahrenheit, double celsius) { PrintHeader(); DisplayResult (fahrenheit, celsius); }

Slide 42 Top-Down Design Example (Cont.) The program (Cont.): void PrintHeader (void) { printf(“Fahrenheit\tCelsius\n”); } void DisplayResult (double fahrenheit, double celsius) { printf(“%10.2lf\t%10.2lf\n”, fahrenheit, celsius); }

Slide 43 Top-Down Design Example (Cont.) Example: Hint on HW #2

Slide 44 References Herbert Schildt: C: The Complete Reference, 4 th ed, Osborne Publishing Deitel & Deitel: C How to Program, 4th ed., Chapter 5 & 8, Prentice Hall