FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

1 Storage Duration and Scope –Local and global variables Storage classes –automatic, static, external, register Todays Material.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C Programming Lecture 7 Functions. Structured Programming b Keep the flow of control in a program as simple as possible. b Use top-down design. Keep decomposing.
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.
1 Review of Class on Oct Outline  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
1 Review of Chapter 3--- Flow of Control  How to specify conditions?  Relational, Equality and Logical Operators  Statements  Statements: compound.
 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.
1 Functions (covered by Chapter 5 in ABC). 2 Type function_name( parameter list ) { Declarations Statements } Function Definition Header body Partitioning.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
1 Chapter 4 (II) Functions and Structured Programming.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
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.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Storage Classes.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2012 CMPE-013/L Functions Gabriel Hugh Elkaim Spring 2012.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Senem Kumova Metin // CS115 // FUNCTIONS continues CHAPTER 5.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
1 Homework / Exam Finish up K&R Chapters 3 & 4 Starting K&R Chapter 5 Next Class HW4 due next class Go over HW3 solutions.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
 2007 Pearson Education, Inc. All rights reserved Random Number Generation  rand function – Load – Returns "random" number between
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
7 주 강의 Functions. Top-down programming type function_name (parameter_list) { declarations statements } int factorial(int n) { int i, product = 1; for.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes.
Functions. Flow of Control Review while for do while goto break & continue switch Relational operators short circuits.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Senem Kumova Metin // CS115 // FUNCTIONS CHAPTER 5.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
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.
A First Book of ANSI C Fourth Edition
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Introduction to C Lecture 4: Functions Alireza Masoum Urmia University Of Technology 2007
C Programming Lecture 8 Call by Reference Scope. Call-by-Reference b For a C function to “effect” (read as “imitate”) call-by- reference: Pointers must.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Functions Course conducted by: Md.Raihan ul Masood
Chapter 7: User-Defined Functions II
C Functions -Continue…-.
Functions and Structured Programming
Functions.
Programmazione I a.a. 2017/2018.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Scope, Parameter Passing, Storage Specifiers
Chapter 6 - Functions Outline 5.1 Introduction
Chapter 7: User-Defined Functions II
Department of Statistics St. Joseph’s College (Autonomous)
Functions.
Presentation transcript:

FUNCTIONS

Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the function construct  A program consists of one or more files  Each file contains zero or more functions, one of them being a main() function.

Function Definition type function_name (parameter list) { declarations statements }  A function definition starts with the type of the function.  If no value is returned, then the type is void.  If NOT void, then the value returned by the function will be converted, if necessary, to this type.  parameter list  a comma-separated list of declarations  formal parameters of the function : function header : function body

Function Definition int factorial(int n) /* header */ { /* body starts here */ int i, product = 1; for (i = 2; i <= n; ++i) product *= i; return product; } void main(void) { … factorial(7); /* The function, factorial(), is called, or invoked */ … }

Function Definition void nothing(void) { } /* this function does nothing */ double twice(double x) { return 2.0 * x; } int all_add(int a, int b)  all_add(int a, int b) { { int c; ….. … return (a+b+c); }

Function Definition  “local” variables vs. “global” variables (internal vs external)  “local” variables : any variables declared in the body of a function  “global” variables : other variables declared external to the function #include int a = 33; /* a is external*/ int main(void) { int b = 77; /* b is local to main() */ printf(“a = %d\n”, a);/* a is global to main() */ printf(“b = %d\n”, b); return 0; }

Function Definition  Important reasons to write programs as collections of many small functions  It is simpler to correctly write a small function to do one job. easier writing & debugging  It is easier to maintain or modify such a program  Small functions tend to be self-documenting and highly readable.

return Statement return; return expression ;  When a return statement is encountered,  execution of the function is terminated and  control is passed back to the calling environment return; return ++a; return (a*b);

return Statement float f(char a, char b, char c) { int i; … return i; /*value returned will be converted to a float*/ } double absolute_value(double x) { if (x>=0.0) return x; else return –x; } while (….) { getchar(); /*get a char, but do nothing with it */ c = getchar(); }

Function Prototypes  Functions should be declared before they are used.  Function prototype  tells the compiler the # and type of argument passed to the function  tells the type of the value returned by the function  allows the compiler to check the code more thoroughly type function_name (parameter type list); double sqrt(double);  Identifiers are optional. void f(char c, int i);  void f(char, int);

Styles for Function Definition Order  A way to write a program in a single file ① #includes and #defines at the top of file ② enumeration types, structures, and unions ③ a list of function prototypes ④ function definitions, starting with main()

Styles for Function Definition Order #include #define N 7 void prn_header(void) { …. } long power(int m, int n) { … } void prn_tbl_powers(int n) { … printf(“%ld”, power(i, j); … } int main(void) { prn_header(); prn_tbl_of_powers(N); return 0; } #include #define N 7 void prn_header(void); long power(int, int); void prn_tbl_powers(int); int main(void) { prn_header(); prn_tbl_of_powers(N); return 0; } void prn_header(void) { …. } long power(int m, int n) { … } void prn_tbl_powers(int n) { … printf(“%ld”, power(i, j); … }

Function Invocation and Call-by-Value  When program control encounters a function name,  the function is called, or, invoked The program control passes to that function  After the function does its work, the program control is passed back to the calling environment.  Functions are invoked  by writing their name and a list of arguments within ().  All arguments for a function are passed “call-by-value”  Each argument is evaluated, and its value is used locally.  The stored value of that variable in the calling environment will NOT be changed.

Function Invocation and Call-by-Value #include int compute_sum(int n); int main(void) { int n = 3, sum; printf(“%d\n”, n); /*3 is printed*/ sum = compute_sum(n); printf(“%d\n”, n); /*3 is printed*/ printf(“%d\n”, sum); /*6 is printed*/ return 0; } int compute_sum(int n) { int sum = 0; for ( ; n>0; --n) /*n is changed*/ sum += n; return sum; }

Developing a Large Program  A large program is typically written in a collection of.h and.c files. #includes #defines … List of function prototypes #include “pgm.h” … #include “pgm.h” … #include “pgm.h” … pgm.h main.cfct.cprn.c Because pgm.h occurs at the top of each.c file, it acts as the “glue” that binds our program together.

Using Assertions  a macro, assert( expr )  in the standard header file assert.h  If expr is false, the system will print a message, and the program will be aborted. #include int f(int a, int b); int g(int c); int main(void) { int a,b,c; … scanf(“%d%d”, &a, &b); … c = f(a,b); assert(c > 0); /*an assertion */ …. } program: program.c:5: main: As sertion 'c > 0' failed. Abort (core dumped)

Scope Rules  Basic rules of scoping  Identifiers are accessible only within the block in which they are declared.  They are unknown outside the boundaries of that block.

Scope Rules { int a = 2; /*outer block a*/ printf(“%d\n”, a); /*2 is printed*/ { int a = 5; /*outer block a*/ printf(“%d\n”, a); /*5 is printed*/ } /*back to the outer block*/ printf(“%d\n”, ++a); /*3 is printed*/ } { int a_outer = 2; printf(“%d\n”, a_outer); { int a_inner = 5; printf(“%d\n”, a_inner); } printf(“%d\n”, ++a_outer); } An outer block name is valid unless an inner block redefines it. If redefined, the outer block name is hidden, or masked, from the inner block

Scope Rules { int a = 1, b = 2, c = 3; printf(“%3d%3d%3d\n”, a, b, c);/* */ { int b = 4; floatc = 5.0; printf(“%3d%3d%5.lf\n”, a, b, c); /* */ a = b; { intc; c = b; printf(“%3d%3d%3d\n”, a, b, c); /* */ } printf(“%3d%3d%5.lf\n”, a, b, c); /* */ } printf(“%3d%3d%3d\n”, a, b, c); /* */ }

Scope Rules  Parallel and Nested Blocks  Two blocks can come one after another The 2 nd block has no knowledge of the var.s declared in the 1 st block. Parallel blocks  Why blocks?  to allow memory for variables to be allocated where needed  Block exit releases the allocated storage { int a, b; … { /* inner block 1 */ float b; … /* int a is known, but not int b */ } … {/* inner block 2 */ float a; … /*int b is known, but not int a*/ /* nothing in inner block 1 is known*/ }

Storage Classes  Every variable and function in C has two attributes  type and storage class  Four storage classes auto externregisterstatic  auto : automatic The most common storage class for variable

Storage Class auto  Variables declared within function bodies are automatic by default  When a block is entered, the system allocates memory for the automatic variables. These variables are “local” to the block  When the block is exited, the memory is automatically released (the value is lost) void f(int m) { int a,b,c; float f; …. }

Storage Class extern  One method of transmitting information across blocks and functions is To Use External variables  When a var. is declared outside a function,  storage is permanently assigned to it.  its storage class is extern  The var. is “global” to all functions declared after it.  Information can be passed into a function two ways ① by use of external variables ② by use of the parameter mechanism

Storage Class extern #include int a = 1, b = 2, c = 3;/* global variables */ /* definition and declaration */ intf(void); int main(void) { printf(“%3d\n”, f());/* 12 is printed */ printf(“%3d%3d%3d\n”, a, b, c);/* is printed */ return 0; } int f(void) { int b, c;/* b and c are local */ a = b = c= 4;/* global b, c are masked */ return (a+b+c); }

Storage Class extern In file file1.c #include int a = 1, b = 2, c = 3;/* external variables */ intf(void); int main(void) { printf(“%3d\n”, f()); printf(“%3d%3d%3d\n”, a, b, c); return 0; } In file file2.c int f(void) { extern int a;/* look for it elsewhere */ int b, c; a = b = c= 4; return (a+b+c); } The keyword extern is used to tell compiler to “look for elsewhere, either in this file or in some other file.”

Definition & Declaration  External Variables  Definition: the variable is created or assigned storage  Declaration: the nature of the variable is stated but no storage is allocated  The scope of an external variable or a function lasts from the point at which it is declared to the end of the file being compiled.  D at a Ty pe s an d O pe ra to rs. 26

Storage Class register  The storage class register  tells the compiler that the associated var.s should be stored in high-speed memory registers  aims to improve execution speed declares var.s most frequently accessed as register { register int i; /*  register i */ for (i = 0; i < LIMIT; i++) { … } } /* block exit will free the register */

Storage Class static  The storage class static  allows a local var. to retain its previous value when the block is reentered.  in contrast to ordinary auto variables void f(void) { static int cnt = 0; ++cnt; if(cnt % 2 == 0) …/* do something */ else …/* do something different */ } The first time the function f() is invoked, cnt is initialized to zero. On function exit, cnt is preserved in memory Whenever f() is invoked again, cnt is not reinitialized

Default Initialization  external and static variables  initialized to zero by the system, if not explicitly initialized by programmers  auto and register variables  usually not initialized by the system  have “garbage” values.

Recursion  A function is recursive if it calls itself, either directly or indirectly #include int sum(int n); int main(void) { int n = 5; printf(“The sum from 1 to %d is %d\n”, n, sum(n)); return 0; } int sum(int n) { if (n <= 1) return n; else return (n + sum(n-1)); }

Recursion #include int factorial(int n); int main(void) { int n = 5; printf(“The factorial from 1 to %d is %d\n”, n, sum(n)); return 0; } int factorial (int n) /*recursive version */ { if (n <= 1) return 1; else return (n * factorial(n-1)); } int factorial (int n) /* iterative version*/ { int product = 1; for (; n > 1 ; --n) product *= n; return product; }