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

Similar documents
Computer Science & Engineering 150A Problem Solving Using Computers

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

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

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

C++ Programming Lecture 11 Functions Part I

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

Lecture 04 FUNCTIONS AND ARRAYS

C Functions. 5.2 Program Modules in C

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

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Structured Programming. Dr. Mohamed Khedr Lecture 4

C Program Structures

ANSI C Programming Simple Programs

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

Introduction to Functions in C. Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department

Chapter 4: Basic C Operators

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

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

Function I/O. Function Input and Output. Input through actual parameters. Output through return value. Input/Output through side effects

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

Outline. Functions. Functions. Predefined Functions. Example. Example. Predefined functions User-defined functions Actual parameters Formal parameters

Function I/O. Last Updated 10/30/18

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

CT 229 Java Syntax Continued

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

Variable and Data Type 2

Functions. Systems Programming Concepts

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

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

Computers in Engineering. Moving From Fortran to C Michael A. Hawker

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

Introduction. What is function? Multiple functions form a larger program Modular programming

2 Making Decisions. Store the value 3 in memory location y

Lecture 04 FUNCTIONS AND ARRAYS

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

Standard Library Functions Outline

Chapter 6 - Notes User-Defined Functions I

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

CSE123. Program Design and Modular Programming Functions 1-1

1 Introduction to C part I

Fundamentals of Programming & Procedural Programming

Programming and Data Structure

ECET 264 C Programming Language with Applications

Unit 7. Functions. Need of User Defined Functions

Tutorial No. 2 - Solution (Overview of C)

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Beginning C Programming for Engineers

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

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

Goals for This Lecture:

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

The C standard library

Introduction to Engineering gii

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

C Programs: Simple Statements and Expressions

Question 2. [5 points] Given the following symbolic constant definition

Lecture 5. Functions II. Functions with Arguments. CptS 121 Summer 2016 Armen Abnousi

C introduction: part 1

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls

Functions. A function is a subprogram that performs a specific task. Functions you know: cout << Hi ; cin >> number;

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

C Programming for Engineers Functions

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Chapter Procedural Abstraction and Functions That Return a Value. Overview. Top-Down Design. Benefits of Top Down Design.

Chapter 4. Procedural Abstraction and Functions That Return a Value

CS110D: PROGRAMMING LANGUAGE I

(2-2) Functions I H&K Chapter 3. Instructor - Andrew S. O Fallon CptS 121 (January 18, 2019) Washington State University

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

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

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

Fundamentals of Programming Session 4

Chapter 2. Outline. Simple C++ Programs

CSE 230 Intermediate Programming in C and C++ Functions

Lecture 2: C Programming Basic

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

CpSc 1111 Lab 6 Conditional Statements, Loops, the Math Library, and Random Numbers What s the Point?

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

9 Using Equation Networks

CS113: Lecture 4. Topics: Functions. Function Activation Records

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 12, FALL 2012

Methods CSC 121 Fall 2016 Howard Rosenthal

Expressions. Eric McCreath

Algorithms and Programming I. Lecture#12 Spring 2015

Slide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary


A. Introduction to Function 1. Modular Programming input processing output functions library functions 2. Function 1. Benefit of Using Functions

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Methods CSC 121 Fall 2014 Howard Rosenthal

OUTLINE. Review Functions Pointers Function calls Array Pointers Pointer Arrays Data Structures and dynamic Memory Function Pointers quicksort example

Maths Functions User Manual

Methods CSC 121 Spring 2017 Howard Rosenthal

Chapter 2: Overview of C. Problem Solving & Program Design in C

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

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

Transcription:

Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Functions Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Chapter 3 3.1 Building Programs from Existing Information 3.2 Library Functions 3.4 Functions without Arguments 3.5 Functions with Arguments 3.6 Common Programming Errors 2 / 1 Existing Information Programmers seldom start off writing completely original programs. Often the solution can be developed from information that already exists or from the solution to another problem. No point in reinventing the wheel Designing pseudocode generates important information before you even begin to code a program. A description of a problem s data requirements A description of a problem s solution algorithm This provides a starting point in coding your program. What portions of this program can be taken care of by standard library functions? What portions of this code can be grouped into a stand-alone function? 3 / 1

Library Functions C has several standard libraries that have been developed over the last several decades Input/Output libraries Math libraries Helpful standard libraries etc. Libraries are provided for the purpose of code reuse Highly optimized and thoroughly tested 4 / 1 Predefined Functions and Code Reuse A primary goal of software engineering is to write error-free code. This is facilitated by code reuse, reusing program fragments that have already been written and tested C promotes reuse by providing many predefined functions that can be used to perform mathematical computations. 5 / 1 Standard Math Library Functions such as sqrt are found in the standard math library to perform the square root computation. The function call in the assignment statement y = sqrt(x); activates the code for function sqrt, passing x to the function. After execution, the result of the function is substituted for the function call. If x is 16.0, the assignment statement above is evaluated as follows: 16.0 is evaluated to 4.0, the call sqrt(x) is replaced with 4.0, and then y takes the value 4.0. To include, use: #include<math.h> Note: Generally, when using the math library, you must use -lm: prompt:>gcc -lm mymathprogram.c (though cse s gcc doesn t require it) 6 / 1

C Library Functions Examples Function #include Description abs(x) stdlib.h integer absolute value x fabs(x) math.h double absolute value ceil(x) math.h Returns ceiling value, ceil(46.3)=47.0 floor(x) math.h Returns floor value, floor(46.3)=46.0 cos(x) sin(x) math.h Input in radians tan(x) exp(x) math.h Returns e x log(x) math.h Natural log: ln(x), x > 0 log10(x) math.h Log base 10: log 10 (x), x > 0 (Recall that log k (x) = log 10 (x)/ log 10 (k)) 7 / 1 pow(x,y) math.h Returns x y sqrt(x) math.h Returns square root. Function Specifics abs(x) is the only function listed with an int value argument and result. All others have both double as the argument and double as the result. tan(x), cos(x) and sin(x) take as their input the radians If a function is called with an argument that is not the argument s data type, the argument is converted to the required data type before it is used. Conversion of type int to type double cause no problems, but a conversion of type double to type int leads to the loss of any fractional part. The arguments for sqrt, log and log10 must be positive. Invalid inputs may result in NaN, inf, -inf, etc. 8 / 1 Functions Without Arguments In C, functions have three important parts: Function Prototypes - contains the name, return type and arguments of a function Function Definitions - the implementation of the function Placement of Functions in a Program - how do we use functions? 9 / 1

Functions without Arguments Top-Down Design: Problem-solving method in which one breaks a large problem into smaller, simpler, subproblems. Programmers utilize top-down design in their programs by defining their own functions. Write one function (subprogram) for each subproblem Case Study, Section 3.3 To begin, we focus on simple functions that have no arguments and no return value (void functions). 10 / 1 Function Prototypes As with other identifiers in C, a function must be declared before it can be referenced (used). One way to declare a function is to insert a function prototype before the main function. Standard library functions (printf, scanf, sqrt, etc.) are prototyped in header (.h) files A function prototype tells C compiler the data type of the function, the function name, and information (number, data type) about the arguments that the function expects. Data Type of the function is the type of value returned by the function. Functions that return no value are of type void 11 / 1 Function Definitions The function prototype (declaration) does not specify the function operation (what it does). The variable declaration: int c; does not tell you how c will be used. To do this, you need to provide a definition for each function subprogram (similar to the definition of the main function). The function heading is similar to the function prototype, but not ended by the symbol ;. The function body (enclosed in braces) contains the implementation of the function (specifies what it does) The return statement is optional for void functions 12 / 1

Function Prototypes & Definition Example 13 / 1 1 2 /* function prototype */ 3 void printprograminfo (); 4 5 int main ( void ) 6 { 7... 8 return 0; 9 } 10... 11 12 /* function definition */ 13 void printprograminfo ( void ) 14 { 15 printf (" Program Example for CSCE 150 A\n"); 16 printf (" copyright (c) C. Bourke 2009\ n"); 17 return ; 18 } Function Definition Scope Each function body may contain declarations for its own variables. These variables are considered local to the function They can be referenced only within the function. No other function has access to their values and they are destroyed after the return statement. This is known as a variable s scope 14 / 1 Function Definition Scope Example 1 /* function prototype */ 2 void hereisafunction (); 3 4 int main ( void ) 5 { 6 int x; 7... 8 } 9 10 /* function definition */ 11 void hereisafunction ( void ) 12 { 13 int y; 14... 15 } 15 / 1 main cannot see y and hereisafunction cannot see x

Placement of Functions in a Program The placement of function prototypes and definitions is important. The compiler must be told that a function exists before it can be used Function prototypes should appear after the #include and #define preprocessor directives and before the main function. The function definitions follow the end of the main function. The relative order of the function definitions does not affect their order of execution; that is determined by the order of the function call statements. 16 / 1 Full Example 1 /* Program Hello, World */ 2 # include <stdio.h> 3 4 /* Function Prototypes */ 5 void Hello_World ( void ); 6 7 int main ( void ) { 8 Hello_World (); 9 return 0; 10 } 11 12 /* Function Definitions */ 13 /* Prints Hello, World */ 14 void Hello_World ( void ) { 15 printf (" Hello, World \n"); 16 } 17 / 1 Displaying User Instructions Simple functions have limited capability. Without the ability to pass information into or out of a function, we can use functions only to do local computation Example: display multiple lines of program output, instructions to a program user or a title page or a special message that precedes a program s result. 18 / 1

Functions with Input Arguments void Functions with Input Arguments Functions with Input Arguments and a Single Result Functions with Multiple Arguments Argument List Correspondence The Function Data Area Testing Functions Using Drivers 19 / 1 Functions with Input Arguments Arguments of a function are used to carry information into the function subprogram from the main function (or from another function subprogram) or to return multiple results computed by a function subprogram. Arguments that carry information into the function are called input arguments Arguments that return results are called output arguments and are denoted by the ampersand & (e.g. used in scanf) We can also return a single result from a function by executing a return statement in the function body. This is preferred over output arguments unless the latter are absolutely necessary 20 / 1 void Functions with Input Arguments Functions without arguments are too limited. We can use a void function with an argument to dress up our program output by having the function display its argument value in a more attractive way. (Recall that a void function does not return a result.) 21 / 1

void Functions with one Input Argument 1 /* Displays a real number in a box. */ 2 3 void print_rboxed ( double rnum ) 4 { 5 printf ("+---------+\n"); 6 printf (" \n"); 7 printf (" %7.2f \ n", rnum ); 8 printf (" \n"); 9 printf ("+---------+\n"); 10 } 22 / 1 Functions with Input Argument and a Single Result C functions can only ever return one value sqrt(x), abs(x), pow(x,y), etc. return one value of type double May return any built-in type or user-defined type Problem Design two functions to compute the area and circumference of a circle using one input argument to each (the radius). 23 / 1 Answer 1 double find_circum ( double r) 2 { 3 return (2.0 * PI * r); 4 } 5 6 double find_area ( double r) 7 { 8 return (PI * pow (r,2)); 9 } 24 / 1

Answer (continued) Each function heading begins with the reserved word double Indicates both return a double-type number Both function bodies consist of a single return statement. Its assumed that PI is defined via a global preprocessor directive. Utilizes the standard math library We would call this function just like with math library functions: areaofcircle = find_area(3.5); 25 / 1 Additional Considerations What happens if we pass a negative value to find_area? Can we make it more efficient? Can we make it more readable? 26 / 1 Better Area Function 1 /* 2 * Compute the area of a circle 3 * Input : double radius 4 * Return Value : area 5 */ 6 double find_area ( double radius ) 7 { 8 double area ; 9 if( radius < 0) 10 area = 0.0; 11 else 12 area = 3.14159265 * radius * radius ; 13 return area ; 14 } 27 / 1

Functions with Multiple Arguments Functions find_area and find_circum each have a single argument. We can also define functions with multiple arguments. We can have as many arguments (inputs) as we want, but the number is fixed. Can have exceptions to this (e.g. printf, scanf), but this is not common 28 / 1 1 /* 2 * Multiplies its first argument by 10 raised 3 * its second power, i.e. 4 * x * 10^y, 5 * where x is the first argument and y 6 * is the second argument 7 */ 8 double scale ( double x, int y) 9 { 10 double scale_factor ; 11 scale_factor = pow (10, y); 12 return (x * scale_factor ); 13 } 29 / 1 Argument List Correspondence When using multiple-argument functions, be careful to include the correct number of arguments in the function call. The order or the actual arguments used in the function call must correspond to the order of the formal parameters listed in the function prototype. The type of each argument must match when calling the function: do not pass a double into a function where the formal parameter is data type int 30 / 1

The Function Data Area Each time a function call is executed, an area of memory is allocated (system stack) for storage of that function s data. Included in the function data area are storage cells for its formal parameters and any local variables that may be declared in the function. The function data are always lost when the function terminates; it is recreated empty when the function is called again 31 / 1 Testing Functions Using Drivers A function is an independent program module, meaning it can be tested separately from the program that uses it. To run such a test, you should write a short driver function. A driver function defines the function arguments, calls the functions, and displays the value returned. 32 / 1 Wrap-Up Program Style Order of Execution of Function Subprograms and Main Function Advantages of Using Function Subprograms Displaying User Instructions 33 / 1

Order or Execution Prototypes for the function subprograms appear before the main function so that the compiler can process the function prototypes before it translates the main function. The information in each prototype enables the compiler to correctly translate a call to that function. After compiling the main function, the compiler translates each function subprogram. During translation, when the compiler reaches the end of a function body, it inserts a machine language statement that causes a transfer of control back from the function to the calling statement. 34 / 1 Advantages of Using Function Subprograms There are many advantages to using function subprograms. General programming Procedural Abstraction Reuse of Function Subprograms 35 / 1 General Programming Their availability changes the way in which an individual programmer organizes the solution to a programming problem For a team of programmers working together on a large problem, each member can focus on solving a set of subproblems. Simplify programming tasks by providing building blocks for new programs. 36 / 1

Procedural Abstraction 37 / 1 Function subprograms allow us to remove from the main function the code that provides the detailed solution to a subproblem. Because these details are provided in the function subprograms and not in the main function, we can write the main function as a sequence of function call statements as soon as we have specified the initial algorithm and before we refine any of the steps. We should delay writing the function for an algorithm step until we have finished refining the previous step. With this approach to program design, called procedural abstraction, we defer implementation details until we are ready to write an individual function subprogram. Focusing on one function at a time is much easier than trying to write the complete program at once. E.g. program circle in textbook Reuse of Function Subprograms Another advantage of using function subprograms is that functions can be executed more than once in a program. Finally, once you have written and tested a function, you can use it in other programs or functions. 38 / 1 Common Programming Errors 39 / 1 Remember to use a #include preprocessor directive for every standard library from which you are using functions. Use appropriate options for the compiler to link in the libraries you need Place prototypes for your own function subprogram in the source file preceding the main function; place the actual function definitions after the main function. The acronym not summarizes the requirements for argument list correspondence: Provide the required number of arguments, Make sure the order of arguments is correct, and Each function argument is the correct type or that conversion to the correct type will lose no information. Also be careful in using functions that are undefined on some range of values.

Questions? Questions? 40 / 1 Exercise Problem Design a program that takes prompts for inputs, a, b, c and uses two functions quadraticrootone, quadraticroottwo which return the real-valued roots of the quadratic equation, Hint: recall the quadratic equation: ax 2 + bx + c x = b ± b 2 4ac 2a Be sure to format your output (you may assume that the input doesn t result in any complex roots, that is, b 2 4ac). 41 / 1