 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: Evan Korth New York University.
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.
Introduction to Computers and Programming Introduction to Methods in Java.
 2007 Pearson Education, Inc. All rights reserved C Functions.
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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
Function (L16) * Mathematical Library Functions * Program Components in C++ * Motivations for Functionalizing a Program * Function Prototype * Function.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
1 Review (Week1) C++_ the unit of programming is the class from which objects are eventually instantiated. C++ classes contain functions that implement.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
 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.
Functions. 3Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Craps!. Example: A Game of Chance Craps simulator Rules – Roll two dice 7 or 11 on first throw, player wins 2, 3, or 12 on first throw, player loses 4,
1 Lecture 3 Part 1 Functions with math and randomness.
© 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.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
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 C Functions.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Header files and Library Functions) Outline.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 5.3Math Library Functions Math library functions –perform.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions 3.4Functions 3.5Function Definitions 3.6Function.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
TMC1414/TMC1413 I NTRODUCTION T O P ROGRAMMING Lecture 06 Function.
 2000 Prentice Hall, Inc. All rights reserved. 5.2Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions.
Dale Roberts CSCI 230 Functions Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Introduction Modules Small pieces of a problem ▴ e.g., divide and conquer Facilitate design, implementation, operation and maintenance of large programs.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Dale Roberts CSCI N305 Functions Declarations Department of Computer and Information Science, School of Science, IUPUI.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Introduction Program Components in C++ Math Library Functions Functions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Lecture 12: Dividing Up Work. Why Using Functions Divide-and-conquer making large program development more manageable. Software reusability Use existing.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Functions Course conducted by: Md.Raihan ul Masood
Dr. Shady Yehia Elmashad
5 C Functions.
Chapter 3 - Functions Outline 3.1 Introduction
CSC113: Computer Programming (Theory = 03, Lab = 01)
Deitel- C:How to Program (5ed)
Dr. Shady Yehia Elmashad
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
Chapter 5 - Functions Outline 5.1 Introduction
Dr. Shady Yehia Elmashad
Functions Declarations CSCI 230
توابع در C++ قسمت اول اصول كامپيوتر 1.
Chapter 6 - Functions Outline 5.1 Introduction
Chapter 3 - Functions Outline 3.1 Introduction
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files 8Calling Functions: Call by Value and Call by Reference 9Random Number Generation 10Example: A Game of Chance 11Storage Classes 12Scope Rules 13Recursion 14Example Using Recursion: The Fibonacci Series 15Recursion vs. Iteration

 2000 Prentice Hall, Inc. All rights reserved. 1Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program

 2000 Prentice Hall, Inc. All rights reserved. 2Program Modules in C Functions –Modules in C –Programs written by combining user-defined functions with library functions C standard library has a wide variety of functions Makes programmer's job easier - avoid reinventing the wheel

 2000 Prentice Hall, Inc. All rights reserved. 2Program Modules in C (II) Function calls –Invoking functions Provide function name and arguments (data) Function performs operations or manipulations Function returns results –Boss asks worker to complete task Worker gets information, does task, returns result Information hiding: boss does not know details

 2000 Prentice Hall, Inc. All rights reserved. 3Math Library Functions Math library functions –perform common mathematical calculations –#include Format for calling functions FunctionName (argument); If multiple arguments, use comma-separated list –printf( "%.2f", sqrt( ) ); Calls function sqrt, which returns the square root of its argument All math functions return data type double –Arguments may be constants, variables, or expressions

 2000 Prentice Hall, Inc. All rights reserved. Math Library Functions double acos(double x) -- Compute arc cosine of x. double asin(double x) -- Compute arc sine of x. double atan(double x) -- Compute arc tangent of x. double atan2(double y, double x) -- Compute arc tangent of y/x. double ceil(double x) -- Get smallest integral value that exceeds x. double cos(double x) -- Compute cosine of angle in radians. double cosh(double x) -- Compute the hyperbolic cosine of x. div_t div(int number, int denom) -- Divide one integer by another. double exp(double x -- Compute exponential of x double fabs (double x ) -- Compute absolute value of x. double floor(double x) -- Get largest integral value less than x. double fmod(double x, double y) -- Divide x by y with integral quotient and return remainder. double frexp(double x, int *expptr) -- Breaks down x into mantissa and exponent of no. labs(long n) -- Find absolute value of long integer n. double ldexp(double x, int exp) -- Reconstructs x out of mantissa and exponent of two. ldiv_t ldiv(long number, long denom) -- Divide one long integer by another. double log(double x) -- Compute log(x). double log10 (double x ) -- Compute log to the base 10 of x. double modf(double x, double *intptr) -- Breaks x into fractional and integer parts. double pow (double x, double y) -- Compute x raised to the power y. double sin(double x) -- Compute sine of angle in radians. double sinh(double x) - Compute the hyperbolic sine of x. double sqrt(double x) -- Compute the square root of x. void srand(unsigned seed) -- Set a new seed for the random number generator (rand). double tan(double x) -- Compute tangent of angle in radians. double tanh(double x) -- Compute the hyperbolic tangent of x.

 2000 Prentice Hall, Inc. All rights reserved. 4Functions Functions –Modularize a program –All variables declared inside functions are local variables Known only in function defined –Parameters Communicate information between functions Local variables Benefits –Divide and conquer Manageable program development –Software reusability Use existing functions as building blocks for new programs Abstraction - hide internal details (library functions) –Avoids code repetition

 2000 Prentice Hall, Inc. All rights reserved. 5Function Definitions Function definition format return-value-type function-name ( parameter-list ) { declarations and statements } –Function-name: any valid identifier –Return-value-type: data type of the result (default int ) void - function returns nothing –Parameter-list: comma separated list, declares parameters (default int )

 2000 Prentice Hall, Inc. All rights reserved. 5Function Definitions (II) Function definition format (continued) return-value-type function-name ( parameter-list ) { declarations and statements } –Declarations and statements: function body (block) Variables can be declared inside blocks (can be nested) Function can not be defined inside another function –Returning control If nothing returned –return; –or, until reaches right brace If something returned –return expression ;

 2000 Prentice Hall, Inc. All rights reserved. Outline 1. Function prototype (3 parameters) 2. Input values 2.1 Call function 3. Function definition Program Output 1/* 2 Finding the maximum of three integers */ 3#include 4 5int maximum( int, int, int ); /* function prototype */ 6 7int main() 8{8{ 9 int a, b, c; printf( "Enter three integers: " ); 12 scanf( "%d%d%d", &a, &b, &c ); 13 printf( "Maximum is: %d\n", maximum( a, b, c ) ); return 0; 16} 17 18/* Function maximum definition */ 19int maximum( int x, int y, int z ) 20{ 21 int max = x; if ( y > max ) 24 max = y; if ( z > max ) 27 max = z; return max; 30} Enter three integers: Maximum is: 85

 2000 Prentice Hall, Inc. All rights reserved. 6Function Prototypes Function prototype –Function name –Parameters - what the function takes in –Return type - data type function returns (default int ) –Used to validate functions –Prototype only needed if function definition comes after use in program int maximum( int, int, int ); Takes in 3 int s Returns an int Promotion rules and conversions –Converting to lower types can lead to errors

 2000 Prentice Hall, Inc. All rights reserved. 7Header Files Header files –contain function prototypes for library functions –,, etc –Load with #include #include Custom header files –Create file with functions –Save as filename.h –Load in other files with #include "filename.h" –Reuse functions

 2000 Prentice Hall, Inc. All rights reserved. 8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value –Copy of argument passed to function –Changes in function do not effect original –Use when function does not need to modify argument Avoids accidental changes Call by reference –Passes original argument –Changes in function effect original –Only used with trusted functions For now, we focus on call by value

 2000 Prentice Hall, Inc. All rights reserved. 9Random Number Generation rand function –Load –Returns "random" number between 0 and RAND_MAX (at least 32767) i = rand(); –Pseudorandom Preset sequence of "random" numbers Same sequence for every function call Scaling –To get a random number between 1 and n 1 + ( rand() % n ) rand % n returns a number between 0 and n-1 Add 1 to make random number between 1 and n 1 + ( rand() % 6) // number between 1 and 6

 2000 Prentice Hall, Inc. All rights reserved. 9Random Number Generation (II) srand function – –Takes an integer seed - jumps to location in "random" sequence srand( seed ); –srand( time( NULL ) ); //load time( NULL )- time program was compiled in seconds "randomizes" the seed

 2000 Prentice Hall, Inc. All rights reserved. Outline 1. Initialize seed 2. Input value for seed 2.1 Use srand to change random sequence 2.2 Define Loop 3. Generate and output random numbers 1/* 2 Randomizing die-rolling program */ 3#include 4#include 5 6int main() 7{7{ 8 int i; 9 unsigned seed; printf( "Enter seed: " ); 12 scanf( "%u", &seed ); 13 srand( seed ); for ( i = 1; i <= 10; i++ ) { 16 printf( "%10d", 1 + ( rand() % 6 ) ); if ( i % 5 == 0 ) 19 printf( "\n" ); 20 } return 0; 23}

 2000 Prentice Hall, Inc. All rights reserved. Outline Program Output Enter seed: Enter seed: Enter seed:

 2000 Prentice Hall, Inc. All rights reserved. 10Example: A Game of Chance Craps simulator Rules –Roll two dice 7 or 11 on first throw, player wins 2, 3, or 12 on first throw, player loses 4, 5, 6, 8, 9, 10 - value becomes player's "point" –Player must roll his point before rolling 7 to win

 2000 Prentice Hall, Inc. All rights reserved. Outline 1. rollDice prototype 1.1 Initialize variables 1.2 Seed srand 2. Define switch statement for win/loss/continue 2.1 Loop 1/* 2 Craps */ 3#include 4#include 5#include 6 7int rollDice( void ); 8 9int main() 10{ 11 int gameStatus, sum, myPoint; srand( time( NULL ) ); 14 sum = rollDice(); /* first roll of the dice */ switch ( sum ) { 17 case 7: case 11: /* win on first roll */ 18 gameStatus = 1; 19 break; 20 case 2: case 3: case 12: /* lose on first roll */ 21 gameStatus = 2; 22 break; 23 default: /* remember point */ 24 gameStatus = 0; 25 myPoint = sum; 26 printf( "Point is %d\n", myPoint ); 27 break; 28 } while ( gameStatus == 0 ) { /* keep rolling */ 31 sum = rollDice(); 32

 2000 Prentice Hall, Inc. All rights reserved. Outline 2.2 Print win/loss Program Output 33 if ( sum == myPoint ) /* win by making point */ 34 gameStatus = 1; 35 else 36 if ( sum == 7 ) /* lose by rolling 7 */ 37 gameStatus = 2; 38 } if ( gameStatus == 1 ) 41 printf( "Player wins\n" ); 42 else 43 printf( "Player loses\n" ); return 0; 46} 47 48int rollDice( void ) 49{ 50 int die1, die2, workSum; die1 = 1 + ( rand() % 6 ); 53 die2 = 1 + ( rand() % 6 ); 54 workSum = die1 + die2; 55 printf( "Player rolled %d + %d = %d\n", die1, die2, workSum ); 56 return workSum; 57} Player rolled = 11 Player wins

 2000 Prentice Hall, Inc. All rights reserved. Outline Program Output Player rolled = 12 Player loses Player rolled = 10 Point is 10 Player rolled = 6 Player rolled = 11 Player rolled = 6 Player rolled = 10 Player wins Player rolled = 4 Point is 4 Player rolled = 5 Player rolled = 9 Player rolled = 10 Player rolled = 9 Player rolled = 3 Player rolled = 7 Player loses