BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

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

CSE123. Program Design and Modular Programming Functions 1-1

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

C Functions. 5.2 Program Modules in C

Functions. Systems Programming Concepts

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

C Functions Pearson Education, Inc. All rights reserved.

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

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

Chapter 3 - Functions

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

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Lecture 04 FUNCTIONS AND ARRAYS

ECET 264 C Programming Language with Applications

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

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Chapter 3 - Functions

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

C Programs: Simple Statements and Expressions

Introduction to Programming

Functions and Recursion

Methods: A Deeper Look

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

Function Call Stack and Activation Records

C: How to Program. Week /Apr/16

6.5 Function Prototypes and Argument Coercion

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Chapter 5 C Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Methods (Deitel chapter 6)

C++ Programming Lecture 11 Functions Part I

Methods (Deitel chapter 6)

Introduction to C Language

Tutorial 5. PDS Lab Section 16 Autumn Functions The C language is termed as function-oriented programming

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

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

C Functions. Object created and destroyed within its block auto: default for local variables

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

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

CS3157: Advanced Programming. Outline

Computer Programming

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Functions and Recursion

Programming for Engineers Functions

Fundamentals of Programming & Procedural Programming

CSE2301. Functions. Functions and Compiler Directives

Review: Constants. Modules and Interfaces. Modules. Clients, Interfaces, Implementations. Client. Interface. Implementation

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Language Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

Programming in C Quick Start! Biostatistics 615 Lecture 4

Unit 7. Functions. Need of User Defined Functions

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Programming in C. Part 1: Introduction

CSE 230 Intermediate Programming in C and C++ Functions

Assoc. Prof. Dr. Tansu FİLİK

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

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

Lab Instructor : Jean Lai

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

Fundamentals of Programming Session 12

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

Programming for Engineers Introduction to C

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Introduction to C Final Review Chapters 1-6 & 13

Downloaded from Chapter 2. Functions

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

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

This document is a preview generated by EVS

1001ICT Introduction To Programming Lecture Notes

C: How to Program. Week /Apr/23

Fundamentals of Programming. Lecture 3: Introduction to C Programming

CT 229 Java Syntax Continued

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 1

This is a preview - click here to buy the full publication INTERNATIONAL STANDARD. Programming languages - C. Langages de programmation - C

ANSI C Programming Simple Programs

Introduction to Programming Systems

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer


2. Numbers In, Numbers Out

Functions in C C Programming and Software Tools

Language Design COMS W4115. Prof. Stephen A. Edwards Fall 2006 Columbia University Department of Computer Science

Methods CSC 121 Fall 2016 Howard Rosenthal

Beginning C Programming for Engineers

from Appendix B: Some C Essentials

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Chapter 15 - C++ As A "Better C"

Holtek C and ANSI C Feature Comparison User s Guide

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

A Fast Review of C Essentials Part I

Transcription:

BIL 104E Introduction to Scientific and Engineering Computing Lecture 4

Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions Modules in C Programs combine user-defined functions with library functions C standard library has a wide variety of functions 10/4/11 Lecture 4 2

Math Library Functions Math library functions perform common mathematical calculations #include <math.h> Format for calling functions FunctionName( argument ); If multiple arguments, use comma-separated list printf( "%.2f", sqrt( 900.0 ) ); 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 10/4/11 Lecture 4 3

Math Library Functions Function Description Example sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 exp( x ) exponential function e x exp( 1.0 ) is 2.718282 exp( 2.0 ) is 7.389056 log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( x ) logarithm of x (base 10) log10( 1.0 ) is 0.0 log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 fabs( x ) absolute value of x fabs( 5.0 ) is 5.0 fabs( 0.0 ) is 0.0 fabs( -5.0 ) is 5.0 ceil( x ) floor( x ) rounds x to the smallest integer not less than x rounds x to the largest integer not greater than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 pow( x, y ) x raised to power y (x y ) pow( 2, 7 ) is 128.0 pow( 9,.5 ) is 3.0 fmod( x, y ) remainder of x/y as a floating point number sin( x ) cos( x ) tan( x ) Fig. 5.2 trigonometric sine of x (x in radians) trigonometric cosine of x (x in radians) fmod( 13.657, 2.333 ) is 1.992 sin( 0.0 ) is 0.0 cos( 0.0 ) is 1.0 trigonometric tangent of x tan( 0.0 ) is 0.0 (x in radians) Commonly used math library functions. 10/4/11 Lecture 4 4

User-Defined Functions Functions (or modules) are the sets of statements that typically perform an operation or that compute a value. To maintain simplicity and readability in longer and more complex problem solutions, instead of using one long main function, we develop programs that use a main function plus additional functions. The execution of a program always begins with the main function. Additional functions are called, or invoked, when the program encounters function names. These additional functions must be defined in the file containing the main function or in another file or library of files. After executing the statements in a function, the program execution continues with the statement that called the function. 10/4/11 Lecture 4 5

Advantages of Modular Programming A module can be written and tested separately from other parts of the solution; thus, module development can be done in parallel for large projects. A module is a small part of the solution; thus, testing it separately is easier. Once a module is tested carefully, it does not need to be retested before it can be used in new problem solutions.(reusability) The use of modules usually reduces the length of a program, making it more readable. The use of modules promotes the concept of abstraction, which allows the programmer to hide the details in modules. This allows us to use modules in a functional sense without being concerned about the specific details. 10/4/11 Lecture 4 6

Function Definitions Functions can be defined before or after the main function. However, one function must be completely defined before another function begins; function definitions cannot be nested within each other. A function consists of a definition statement followed by declarations and statements. If the function does not return a value, the type is void. Thus the general form of a function is: return_type function_name (parameter declarations) { declarations; statements; } The parameter declarations represent the information passed to the function. If there are no input parameters (also called arguments), then the parameter declarations should be void. Additional variables used by a function are defined in the declarations. 10/4/11 Lecture 4 7

Function Definitions All functions should include a return statement, which has the following general form: return expression; The expression specifies the 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 potential errors. A void function does not return a value and thus has this general statement: void function_name (parameter declarations) The return statement in a void function does not contain an expression and has the form: return; 10/4/11 Lecture 4 8

Function Prototype Function prototype statements should be included for all functions referenced in a program. The general form of a function prototype is: return_type function_name (parameter_data_types); A function prototype can be included with preprocessor directives, or because a function prototype is defining the type of value being returned by the function, it can also be included with other variable declarations. If a programmer-defined function references other programmerdefined functions, it will also need additional prototype statements. 10/4/11 Lecture 4 9

Function Prototype Header files, such as stdio.h and math.h, contain the prototype statements for many of the functions in the Standard C library. If a program references a large number of programmer-defined functions, it becomes cumbersome to include all the function prototype statements. In these cases, a custom header file can be defined that contains the function prototypes and related symbolic constants. A header file must have a filename that ends with a suffix of.h. The file is then referenced with an include statement using double quotes around the file name. Custom header files are often used to accompany routines that are shared by programmers. 10/4/11 Lecture 4 10

Parameter List The definition statement of a function defines parameters that are required by the function; these are called formal parameters. Any statement that references the function must include values that correspond to the parameters; these are called actual parameters. When the function is referenced the value in the actual parameters are copied to the formal parameters and the steps in the function are executed using the new values in the formal parameters. If a function has more than one parameter, the formal parameters and the actual parameters must match in number, type and order. Valid references to the function can also include expressions and can include other function references 10/4/11 Lecture 4 11

Example Assume that the definition statement of the function f is double f (double x) { } The following references to function f are valid: printf( %f \n, f(x+2.5)); printf( %f \n, f(y)); z = x*x + f(2*x) ; w = f(fabs(y)) ; Here, the formal parameter is still x, but the actual parameter changes depending on the reference selected. 10/4/11 Lecture 4 12

1 /* Fig. 5.3: fig05_03.c 2 Creating and using a programmer-defined function */ 3 #include <stdio.h> 4 5 int square( int y ); /* function prototype */ 6 7 /* function main begins program execution */ 8 int main() 9 { 10 int x; /* counter */ 11 12 /* loop 10 times and calculate and output square of x each time */ 13 for ( x = 1; x <= 10; x++ ) { 14 printf( "%d ", square( x ) ); /* function call */ 15 } /* end for */ 16 17 printf( "\n" ); 18 19 return 0; /* indicates successful termination */ 20 21 } /* end main */ 22 23 /* square function definition returns square of an integer */ 24 int square( int y ) /* y is a copy of argument to function */ 25 { 26 return y * y; /* returns square of y as an int */ 27 28 } /* end function square */ 1 4 9 16 25 36 49 64 81 100 10/4/11 Lecture 4 13

1 /* Fig. 5.4: fig05_04.c 2 Finding the maximum of three integers */ 3 #include <stdio.h> 4 5 int maximum( int x, int y, int z ); /* function prototype */ 6 7 /* function main begins program execution */ 8 int main() 9 { 10 int number1; /* first integer */ 11 int number2; /* second integer */ 12 int number3; /* third integer */ 13 14 printf( "Enter three integers: " ); 15 scanf( "%d%d%d", &number1, &number2, &number3 ); 16 17 /* number1, number2 and number3 are arguments 18 to the maximum function call */ 19 printf( "Maximum is: %d\n", maximum( number1, number2, number3 ) ); 20 21 return 0; /* indicates successful termination */ 22 23 } /* end main */ 24 10/4/11 Lecture 4 14

25 /* Function maximum definition */ 26 /* x, y and z are parameters */ 27 int maximum( int x, int y, int z ) 28 { 29 int max = x; /* assume x is largest */ 30 31 if ( y > max ) { /* if y is larger than max, assign y to max */ 32 max = y; 33 } /* end if */ 34 35 if ( z > max ) { /* if z is larger than max, assign z to max */ 36 max = z; 37 } /* end if */ 38 39 return max; /* max is largest value */ 40 41 } /* end function maximum */ Enter three integers: 22 85 17 Maximum is: 85 Enter three integers: 85 22 17 Maximum is: 85 Enter three integers: 22 17 85 Maximum is: 85 10/4/11 Lecture 4 15

Header Files Header files Contain function prototypes for library functions <stdlib.h>, <math.h>, etc Load with #include <filename> #include <math.h> Custom header files Create file with functions Save as filename.h Load in other files with #include "filename.h" Reuse functions 10/4/11 Lecture 4 16

Header Files Standard library header Explanation <assert.h> Contains macros and information for adding diagnostics that aid program debugging. <ctype.h> Contains function prototypes for functions that test characters for certain properties, and function prototypes for functions that can be used to convert lowercase letters to uppercase letters and vice versa. <errno.h> Defines macros that are useful for reporting error conditions. <float.h> Contains the floating point size limits of the system. <limits.h> Contains the integral size limits of the system. <locale.h> Contains function prototypes and other information that enables a program to be modified for the current locale on which it is running. The notion of locale enables the computer system to handle different conventions for expressing data like dates, times, dollar amounts and large numbers throughout the world. <math.h> Contains function prototypes for math library functions. <setjmp.h> Contains function prototypes for functions that allow bypassing of the usual function call and return sequence. <signal.h> Contains function prototypes and macros to handle various conditions that may arise during program execution. <stdarg.h> Defines macros for dealing with a list of arguments to a function whose number and types are unknown. <stddef.h> Contains common definitions of types used by C for performing certain calculations. <stdio.h> Contains function prototypes for the standard input/output library functions, and information used by them. <stdlib.h> Contains function prototypes for conversions of numbers to text and text to numbers, memory allocation, random numbers, and other utility functions. <string.h> Contains function prototypes for string processing functions. <time.h> Contains function prototypes and types for manipulating the time and date. Fig. 5.6 Some of the standard library header. 10/4/11 Lecture 4 17

Calling Functions: Call by Value and Call by Reference 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 10/4/11 Lecture 4 18

Random Number Generation Function rand function Load <stdlib.h> 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 10/4/11 Lecture 4 19

Random Number Generation srand function <stdlib.h> Takes an integer seed and jumps to that location in its "random" sequence srand( seed ); srand( time( NULL ) );/*load <time.h> */ time( NULL ) Function Returns the time at which the program was compiled in seconds Randomizes" the seed 10/4/11 Lecture 4 20

Random Number Generation Function example 1 /* Fig. 5.7: fig05_07.c 2 Shifted, scaled integers produced by 1 + rand() % 6 */ 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 /* function main begins program execution */ 7 int main() 8 { 9 int i; /* counter */ 10 11 /* loop 20 times */ 12 for ( i = 1; i <= 20; i++ ) { 13 14 /* pick random number from 1 to 6 and output it */ 15 printf( "%10d", 1 + ( rand() % 6 ) ); 16 17 /* if counter is divisible by 5, begin new line of output */ 18 if ( i % 5 == 0 ) { 19 printf( "\n" ); 20 } /* end if */ 21 22 } /* end for */ 23 24 return 0; /* indicates successful termination */ 25 26 } /* end main */ 10/4/11 Lecture 4 21

Random Number Generation Function example 6 6 5 5 6 5 1 1 5 3 6 6 2 4 2 6 2 3 4 1 10/4/11 Lecture 4 22

Local vs Global Variables Local variables are defined within a function and include the formal parameters and any other variables declared in function. A local variable can be accessed only in the function that defined it. A local variable has a value when its function is being executed, but its value is not retained when the function is completed. Global variables are defined outside the main function and other programmer defined functions so they can be accessed by any function within the program. To reference a global or an external variable, a declaration within the function must include the keyword extern before the type designation to tell the computer to look outside the function for the variable. It is optional to use extern designation in the original definition of a global variable. 10/4/11 Lecture 4 23

Local vs Global Variables The memory assigned to an external variable is retained for the duration of the program. Although an external variable can be referenced from a function, using global variables is generally discouraged. In general, parameters are preferred for transferring information to a function because the parameter is evident in the function prototype, whereas the external variable is not visible in the function prototype. The static storage class is used to specify that the memory for a variable should be retained during the entire program execution. Therefore, if a local variable in a function is given a static storage class assignment by using the keyword static before its type specification, the variable will not lose its value when the program exits the function in which it is defined. Summary static: local variables defined in functions. Keep value after function ends Only known in their own function extern: default for global variables and functions Known in any function 10/4/11 Lecture 4 24

Local vs Global Variables Example 1 /* Fig. 5.12: fig05_12.c 2 A scoping example */ 3 #include <stdio.h> 4 5 void uselocal( void ); /* function prototype */ 6 void usestaticlocal( void ); /* function prototype */ 7 void useglobal( void ); /* function prototype */ 8 9 int x = 1; /* global variable */ 10 11 /* function main begins program execution */ 12 int main() 13 { 14 int x = 5; /* local variable to main */ 15 16 printf("local x in outer scope of main is %d\n", x ); 17 18 { /* start new scope */ 19 int x = 7; /* local variable to new scope */ 20 21 printf( "local x in inner scope of main is %d\n", x ); 22 } /* end new scope */ 23 24 printf( "local x in outer scope of main is %d\n", x ); 25 10/4/11 Lecture 4 25

Local vs Global Variables Example 26 uselocal(); /* uselocal has automatic local x */ 27 usestaticlocal(); /* usestaticlocal has static local x */ 28 useglobal(); /* useglobal uses global x */ 29 uselocal(); /* uselocal reinitializes automatic local x */ 30 usestaticlocal(); /* static local x retains its prior value */ 31 useglobal(); /* global x also retains its value */ 32 33 printf( "local x in main is %d\n", x ); 34 35 return 0; /* indicates successful termination */ 36 37 } /* end main */ 38 39 /* uselocal reinitializes local variable x during each call */ 40 void uselocal( void ) 41 { 42 int x = 25; /* initialized each time uselocal is called */ 43 44 printf( "\nlocal x in a is %d after entering a\n", x ); 45 x++; 46 printf( "local x in a is %d before exiting a\n", x ); 47 } /* end function uselocal */ 48 10/4/11 Lecture 4 26

Local vs Global Variables Example 49 /* usestaticlocal initializes static local variable x only the first time 50 the function is called; value of x is saved between calls to this 51 function */ 52 void usestaticlocal( void ) 53 { 54 /* initialized only first time usestaticlocal is called */ 55 static int x = 50; 56 57 printf( "\nlocal static x is %d on entering b\n", x ); 58 x++; 59 printf( "local static x is %d on exiting b\n", x ); 60 } /* end function usestaticlocal */ 61 62 /* function useglobal modifies global variable x during each call */ 63 void useglobal( void ) 64 { 65 printf( "\nglobal x is %d on entering c\n", x ); 66 x *= 10; 67 printf( "global x is %d on exiting c\n", x ); 68 } /* end function useglobal */ 10/4/11 Lecture 4 27

Local vs Global Variables Example local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5 local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 50 on entering b local static x is 51 on exiting b global x is 1 on entering c global x is 10 on exiting c local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 51 on entering b local static x is 52 on exiting b global x is 10 on entering c global x is 100 on exiting c local x in main is 5 10/4/11 Lecture 4 28