Outline. Why do we write functions? Introduction to Functions. How do we write functions? Using Functions. Introduction to Functions March 21, 2006

Similar documents
Programming Language. Functions. Eng. Anis Nazer First Semester

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

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

Outline. First Quiz Results. Exercise Five Goals. Question Three. Questions One and Two. Exercise five if statements February 28, 2006

Chapter 3 - Functions

Introduction to Programming

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

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

Computing and Statistical Data Analysis Lecture 3

C++ Programming Lecture 11 Functions Part I

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Functions and Recursion

Understanding main() function Input/Output Streams

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

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Your first C++ program

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

Department of Computer and Mathematical Sciences. Lab 10: Functions. CS 1410 Intro to Computer Science with C++

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

A SHORT COURSE ON C++

6.096 Introduction to C++

Unit 6. Thinking with Functions

Functions. Lecture 6 COP 3014 Spring February 11, 2018

C Programming for Engineers Functions

Fundamentals of Programming Session 23

Outline. Review Choice Statements. Review Sequential Flow. Review Choice Before Loops. Review Choice After Loops

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

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

(created by professor Marina Tanasyuk) FUNCTIONS

1 Unit 8 'for' Loops

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

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Unit 7. 'while' Loops

C++ Support Classes (Data and Variables)

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

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

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

If Control Construct

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

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.

CSCE 110 PROGRAMMING FUNDAMENTALS

An Introduction to Programming with C++ Sixth Edition. Chapter 8 More on the Repetition Structure

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

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

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

C++ Functions. Last Week. Areas for Discussion. Program Structure. Last Week Introduction to Functions Program Structure and Functions

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Fundamentals of Programming Session 25

Function Usage. Lecture 15 Sections 6.3, 6.4. Robb T. Koether. Hampden-Sydney College. Mon, Oct 1, 2018

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Lecture 8 Tao Wang 1

Computer Programming C++ Classes and Objects 6 th Lecture

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

Getting started with C++ (Part 2)

VuZs Team's Work. CS201 Spring Solved by vuzs Team with Reference Written by Administrator Wednesday, 19 May :52

Computer Science II Lecture 1 Introduction and Background

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

C++ Programming Lecture 1 Software Engineering Group

Lecture 2 Tao Wang 1

Introduction to Scientific Programming with C++

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

In this chapter you will learn:

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

do { statements } while (condition);

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

CSI33 Data Structures

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

CSCE 121 ENGR 112 List of Topics for Exam 1

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.6

CSc Introduction to Computing

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

REVIEW. The C++ Programming Language. CS 151 Review #2

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

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

Introduction to C++ Dr M.S. Colclough, research fellows, pgtas

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 6 - Notes User-Defined Functions I

REPETITION CONTROL STRUCTURE LOGO

Top-Down Design Predefined Functions Programmer-Defined Functions Procedural Abstraction Local Variables Overloading Function Names

Chapter 4 - Notes Control Structures I (Selection)

Chapter 6: Functions

CISC 1110 (CIS 1.5) Introduc2on to Programming Using C++

Chapter 2: Introduction to C++

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Transcription:

Introduction to User-defined Functions Larry Caretto Computer Science 106 Computing in Engineering and Science March 21, 2006 Outline Why we use functions Writing and calling a function Header and body Function prototype Passing information to a function Returning values in the function name 2 Introduction to Functions Library functions like pow, atan and sqrt used previously Statement to set x = yz 3 : x = y * pow( z, 3 ); Note order of arguments important; the call pow( 3, z ) gives 3 z Use #include <cmath> for this function You can write your own functions Why do we write functions? How do we write code to use functions? Why do we write functions? First use of functions was for code like mathematical function calculations Specialized calculation done repeatedly Want to write code only one time Want to be able to pass values of parameters to code and get value back As programs got more complex, breaking code into functions provided a way to organize complex code 3 4 How do we write functions? C++ code is a collection of functions Each function, including main, has the same level of importance in writing code Complete code for each function before starting a new function int main() // body of main int myfunction( ) // body of myfunction 5 Using Functions User-defined functions are used in the same way as library functions Functions are used ( called, invoked ) by placing the name of the function at the correct location in the code The function name is usually followed by a list of variables or constants in parentheses whose values are passed to the function The result of the function is returned in the function name 6 1

Operation of Functions Any function (the caller) can call another function by using the name of the function being called in an expression The statement calling the function sends information from the caller Execution control is transferred to the function being called The function being called returns control and (usually) results to the caller 7 Operation of Functions The function being called uses the information it receives to do a set of calculations or procedures In the usual case, the function being called returns a result to the caller in the location of the function name Example: d = pow(b,2) 4 * a * c; calls the pow function with values of b and 2 and the result b 2 is returned in function name, pow, for further use in an expression 8 Writing and Using Functions Organize the program into individual functions that are called by main Simple example: main calls three functions: (1) input function, (2) calculation function and (3) output function Write code for each function (and main) Write function header to specify information received from calling function Write function body to calculate results and return them to calling function Write function calls that pass data and get results 9 Writing and Using Functions II Library functions, such as pow(x, y) to compute x y, transfer information based on the order of the variables This is true for user-defined functions as well Information transferred from a list of variables in the calling function to a list of variables in the function called Correspondence based on order of variables in function header and statement calling the function 10 Writing Functions The code in a function is works in the same way that the code you have prepared for a single main function All the conventional structures can be used What is new? The first line of the function, the function header, contains a declaration of the variables whose values are passed into the function when it is called 11 Function Basics Each function has a header and a body Header specifies Name of function Type of value returned by the function name List of variables in the function whose values are determined by the calling program Body gives code executed by the function Function prototypes at start of code provide information to compiler Same as header except a semicolon is added at the end Can omit variable names 12 2

Function Basics II Example of header and body double mypow ( double number, // header // Body,in braces contains // actual code for function Header declares data type for function value, function name, and variables whose values will be received from calling function 13 Function Header Header has following syntax: <type> <name> ( <argument list> ) <type> specifies the type of value returned by the function <name> is the name you choose for your function; this name is used to call the function from another function <argument list> specifies type and names of variables in function whose values come from the calling program There is no semicolon at the end of the function header 14 Function Header II Example of function, mypow, a userdefined function to replace pow Pass the number and the power to the function as type double Return the result as type double General header syntax from previous chart <type> <name> ( <argument list> ) double mypow ( double number, Argument List Example on previous chart had two parameters in argument list <type> <name> ( <argument list> ) double mypow ( double number, Function will use number and power as type double variables Values for these variables set by other function that calls (uses) mypow 15 16 Passing arguments Based on order of arguments in function header and in calling statement Recall the library pow function was called as pow(number, power) pow(3,4) = 3 4 but pow(4,3) = 4 3 What is result of following code double number = 3, power = 4; cout << pow( power, number) Result is 4 3 ; only the order counts! 17 The return Statement We have used this statement in main as return EXIT_SUCCESS; The general syntax of this statement is return <value>; <value> may be a constant, a variable or an expression This is value returned to calling program in function name return always transfers control to calling function 18 3

Organization of Function Code Alternative Function Code double result = exp( power * log( number ) ); return result; Place following prototype at top of code ; 19 return exp( power * log( number ) ); Can use following prototype without variable names at top of code double mypow( double, double ); 20 Write a statement that uses the function mypow(double number, double power) to compute z = x + yz 3 z = x + y * mypow( z, 3 ); Write the header for a type bool function named equal that whose first parameter is x, an int variable and whose second parameter, a, is type double bool equal( int x, double a ) 21 Type Name Argument List Another Function Example bool leap( int year ) Header if ( year % 4!= 0 ) return false; else if ( year % 400 == 0 ) return true; else if ( year % 100 == 0 ) return false; else return true; Multiple returns Body 22 Yet Another Function Example Type Name Argument List Header bool leap( int year ) return year % 4 == 0 && ( year % 100!= 0 year % 400 == 0 ); Body This function will have same behavior as one on previous chart User of function does not have to know its internal code, only its input and output 23 Use of bool leap( int year ) bool leap ( int year );// prototype int main() // examples of use cout << Enter a year: ; int y; cin >> y; bool cond = leap( y ); if ( leap( y ) ) if ( leap( y ) && month == 2 ) return EXIT_SUCCESS // leap and other functions go here 24 4

Write a function that takes two type int arguments and returns their difference int diff( int a, int b) return a b; Use this function to compute and print the difference 3 5 cout << diff( 3, 5 ); Write the prototype int diff( int a, int b); 25 Write a function that takes two type double arguments and returns their quotient Use this function to compute 5/3 Write the prototype double div( double a, double b) return a / b; //use: cout << div( 5, 3 ); // prototype: double div(double a, double b); 26 5