Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.

Slides:



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

Modular Programming With Functions
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 5 Functions.
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 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.
 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.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 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.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
C++ for Engineers and Scientists Third Edition
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modular Programming with Functions.
16&17-2 Grasp the concept of top-down programming Identify Function Headers and Prototypes Understand when and where prototypes used Understand how arguments.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
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.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
© 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.
UNIT III. Functions  To divide a big program into a number of relatively smaller and easily manageable subprograms. Each subprogram in C is called a.
CMSC 1041 Functions II Functions that return a value.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
Chapter 6 Functions 6.1 Modular Design A valuable strategy when writing complex programs is to break down the program into several smaller modules. A module.
Modular Programming ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
Engineering Problem Solving with C++, Second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 5 Parameter Passing 11/06/13.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
1 ICS103 Programming in C Lecture 8: Functions I.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
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.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Announcements. Practice questions, with and without solutions will be uploaded by Friday 5 th November, make sure to check them before the weekend \\netstorage\Subjects\ITCA-b\Exam.
Chapter 6 Modularity Using Functions
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 9: Value-Returning Functions
Functions Course conducted by: Md.Raihan ul Masood
User-Written Functions
Functions, Part 2 of 2 Topics Functions That Return a Value
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
User-Defined Functions
C++ for Engineers and Scientists Second Edition
Chapter 5 - Functions Outline 5.1 Introduction
User-defined Functions
Modular Programming with Functions
Chapter 6 - Functions Outline 5.1 Introduction
User-defined Functions
A First Book of ANSI C Fourth Edition
Chapter 9: Value-Returning Functions
Presentation transcript:

Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Modularity

Execution of a program begins in the main function The main function can call other functions –Functions defined in the same file –Function defined in other files or libraries Functions are also referred to as modules A module is a set of statements that performs a task or computes a value

Advantages of using modules Modules can be written and tested separately Large projects can be developed in parallel Reduces length of program, making it more readable Promotes the concept of abstraction, can reduce software development time while increase its quality.

Programmer Defined Functions

Categories of Functions Functions Library Function MathI/OOthers Programmer Defined Functions Functions that Do not return any info Function that return One value Function that return More than one value

Functions Defined to –return a single value to the calling function –perform a task –change the value of the function arguments (call by reference)

Functions Pre-defined –standard libraries Programmer defined

Pre-defined Functions Example #include int main(void) { double angle; printf( “input angle in radians: \n“); scanf(“%lf”, &angle); printf( “\nthe sine of the angle is %f\n“,sin(angle) ); return 0; }//end main

Function Definition return_type Function_name (parameter_declaration) { declarations; statements; } Also, function should include return statement return expression ;

Programmer Defined Functions Terminology Function Prototype –describes how a function is called Function Definition Function Call

Programmer Defined Functions Terminology Actual parameter –used in the function call Formal Parameters –used in function definition Formal parameters must match with actual parameters in order, number and data type

Example:To find max number #include float findMax(float x, float y); int main() { float firstnum,secnum,maxnum; printf("enter your first number:\n"); scanf("%f",&firstnum); printf("enter your second number:\n"); scanf("%f",&secnum); maxnum = findMax(firstnum,secnum); printf("maximum number is :%f\n",maxnum); /* exit program*/ return 0; } /* */ /* function max */ float findMax(float x,float y) { float maxnum; if(x>=y) maxnum=x; else maxnum=y; return(maxnum); } Function Prototype The Function is called here Function Header Variable declaration Find the Max number Return the value Function definitionFunction definition

Function Prototype From example ; float findMax(float x,float y); It informs the compiler that the main function will reference a function named findMax. findMax function expect float parameters and that the findMax function returns a float value.

Function Definition Function consists of definition statement followed by declaration statements /* */ /* function max */ float findMax(float x,float y) { float maxnum; if(x>=y) maxnum=x; else maxnum=y; return(maxnum); } General Form; return_type function_name(parameter declarations) { Declarations; Statements; }

Function Definition Parameter declaration: represents the info passed to the function. If there are no input parameters (arguments), then the parameter declaration should be void. Additional variables used by a function are defined in the braces. The declaration and statements within function are enclosed in braces.

Function Definition Example: Float x,float y: parameters that will be passed to the function. All function should include a statement return (expression);

Function Definition The expression specifies value to be returned to the statement that referenced the function. The expression type should match the return type indicated in the function definition to avoid errors.

Example - factorial function /*function definition n! = n*(n-1)*(n-2)*…*1, 0! = 1 by definition - fact returns n! assumes n is non-negative integer */ int fact(int n) { int fact = 1; while(n>1) { fact = fact*n; n--; }//end while block return(fact); }//end fact Function Definition

Function prototype - prototype can be included with preprocessor directives, or with variable declarations. #include int main(void) { /* Declare variables and function prototypes. */ int n; int fact(int n); printf(“Enter a positive integer\n”); scanf("%i”, &n); if(n>=0) printf(“%i! is %i\n“, n, fact(n) ); return 0; } Note: In this example the function fact is called in the printf statement. Function is called here Function Prototype

Calling a function - the value returned by a function can be assigned to a variable, printed, or used in an expression #include int fact(int n); int main() { /*Declare variables and function prototypes */ int n,factorial; printf("enter positive integer\n"); scanf("%d",&n); if(n>=0) { factorial = fact(n); printf("%i! is %i\n", n, factorial); } return 0; } /* */ /* function Factorial */ int fact(int n) { int fact = 1; while (n>1) { fact=fact*n; n--; } return (fact); } Function is called here

void Functions A void function may be called to perform a particular task (clear the screen) modify data perform input and output A void function does not return a value to the calling program if a return; statement is used (no return value)

Example of void function definition void print_date(int mo, int day, int year) { /*output formatted date */ printf(“%i%i%i\n”, mo, day, year ); return; }

Parameter Passing Call by value –formal parameter receives the value of the actual parameter –function can not change the value of the actual parameter (arrays are an exception) Call by reference –actual parameters are pointers (pointers will be discussed in chapter 6)

Example #include #define PI int main(void) { /*declare variables*/ int k; double a, b, x_incr, new_x; double sinc(double x); /*get interval endpoints from the user*/ printf("enter endpoints a and b (a<b): \n"); scanf("%lf %lf", &a,&b); x_incr = (b-a)/20; /* compute and print table of sinc(x) */ printf("x and sinc(x)\n"); for(k=0;k<=20;k++) { new_x = a + k * x_incr; printf("%f %f\n", new_x, sinc(new_x)); } /* Exit program*/ return 0; } /* */ /*This function evaluates the sinc function */ double sinc(double x) { if (fabs(x) < ) return 1.0; else return sin(PI*x)/(PI*x); } /* */ Function Prototype Statements from main that refer to function Definition of function sinc Function Header

Parameter List When the reference to the sinc function in the printf statement is executed, The value in the actual parameter is copied to the formal parameter, and the steps in the sinc function are executed using the new value in x. printf("%f %f\n", new_x, sinc(new_x)); double sinc(double x) { if (fabs(x) < ) return 1.0; else return sin(PI*x)/(PI*x); }

Parameter List:continue Thus: Variable x  formal parameter new_x  actual parameter Lastly, value returned by sinc function, will be printed.

Parameter List: continue From example, the function reference is call- by-value reference. When a function is made, the value of the actual parameter is passed to the function and is used as the value of the corresponding formal parameter. Note: the value in the formal parameter is not moved back to the actual parameter when the function is completed.

Parameter List: Continue Let say: new_x = 9.0; 9.0 New_xx Actual Parameter Formal Parameter

Practice Consider the following function: int positive(double a, double b, double c) { int count; count=0; if(a>=0) count++; if(b>=0) count++; if(c>=0) count++; return count; } Assume that the function is referenced with the following statements: x=25; total =positive(x,sqrt(x),x-30); 1.Show the memory snapshot of the actual parameters and the formal parameters. 2.What is the new value of total?

Storage Class and Scope Scope refers to the portion of the program in which it is valid to reference a function or a variable or Scope refers to the region in which a declaration is active. Storage class refers to the lifetime of a variable

Scope Local scope - a local variable is defined within a function or a block and can be accessed only within the function or block that defines it. Thus, local scope/variables includes formal parameters and any other variables declared in the function. A local variable can be accessed ONLY in the function that defines it. A local variable has a value when its function is being executed, but its value is not retained when the function is completed.

Scope Global scope - a global variable is defined outside the main function The definition of a global variable is outside of all functions so, it can be accessed by any function within the program.

Storage Class - 4 types automatic - key word auto - default for local variables –Memory set aside for local variables is not reserved when the block in which the local variable was defined is exited. external - key word extern - used for global variables –Memory is reserved for a global variable throughout the execution life of the program. static - key word static –Requests that memory for a local variable be reserved throughout the execution life of the program. The static storage class does not affect the scope of the variable. register - key word register –Requests that a variable should be placed in a high speed memory register.

Random Numbers A sequence of random numbers is not defined by an equation; instead it has certain characteristics that define it. Characteristics include minimum and maximum values also, average. Also, indicate whether the possible values are equally likely to occur or whether some values are more likely to occur than others.

Random Numbers Sequences of random numbers can be generated by experiments:  Tossing coin  Rolling die  Selecting numbered balls  Computer can generate sequence random numbers

Random integer sequence Use rand() function #include Generate random integer 0- RAND_MAX(typically 32767) Rand function has no input arguments and is referenced by rand( ).

Random integer sequence To generate and print a sequence of two random numbers, we could use statements: Printf(“random numbers: %i %i \n”,rand(),rand()); Each time executed, the same two values are printed  pseudo-random.

Random –number seed In order to generate a new sequence of random values each time that it is executed, need to give a new random- number seed to the random number generator. Use srand() function Input argument is unsigned integer #include

Random number-specific range Example 1, number between 0and7 x=rand()%8; Example 2, number between -25 and 25 y=rand()%51-25; Formula, between a and b (b-a+1)+a

Floating-Point sequence Generate floating-point sequence values ((double)rand()/RAND_MAX)*(b-a)+a for interval [a,b]