Computer Programming 1 Functions. Computer Programming 2 Objectives Take a first look at building functions Study how a function is called Investigate.

Slides:



Advertisements
Similar presentations
Calling sequence ESP.
Advertisements

Write a program step by step. Step 1: Problem definition. Given the coordinate of two points in 2-D space, compute and print their straight distance.
Ch. 8 Functions.
Chapter 7: User-Defined Functions II
Lecture 2 Introduction to C Programming
Introduction to C Programming
Introduction to C Programming
Static Methods Chapter 4. Chapter Contents Objectives 4.1 Introductory Example: Old MacDonald Had a Farm … 4.2 Getting Started with Methods 4.3 Example:
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions.
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
Introduction to C Programming
Basic Elements of C++ Chapter 2.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
Review of C++ Programming Part II Sheng-Fang Huang.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Computer Architecture and Operating Systems CS 3230 :Assembly Section Lecture 7 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
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.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Chapter 5 Functions For All Subtasks. Void functions Do not return a value. Keyword void is used as the return type in the function prototype to show.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Introduction to C Programming Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
Parameter Passing Mechanisms Reference Parameters Read § §
1 Simple Functions Writing Reuseable Formulas. In Math Suppose f (x) = 2 x 2 +5Suppose f (x) = 2 x 2 +5 f(5)=?f(5)=? f(5) = 2* =55f(5) = 2*
CPS120: Introduction to Computer Science Functions.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Review 1 List Data Structure List operations List Implementation Array Linked List.
Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Structured Programming (4 Credits) HNDIT Week 2 – Learning Outcomes Design an algorithmic solution for simple problem such as computation of a factorial,
Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used.
Simple Functions Writing Reuseable Formulas. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian.
L what are executable/non-executable statements l out of the ones below which constructs are executable #include p=3.14; const double PI=3.14; int myfunc(int);
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal
© Peter Andreae Java Programs COMP 102 # T1 Peter Andreae Computer Science Victoria University of Wellington.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
A First Book of ANSI C Fourth Edition
1 Types of Programming Language (1) Three types of programming languages 1.Machine languages Strings of numbers giving machine specific instructions Example:
1 A more complex example Write a program that sums a sequence of integers and displays the result. Assume that the first integer read specifies the number.
Computer Programming II Lecture 4. Functions - In C++ we use modules to divide the program into smaller and manageable code. These modules are called.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Instructions for test_function
Chapter Topics The Basics of a C++ Program Data Types
User-Written Functions
Completing the Problem-Solving Process
Programming Fundamental
Basic Elements of C++.
Objectives Identify the built-in data types in C++
CSC113: Computer Programming (Theory = 03, Lab = 01)
Writing Reuseable Formulas
Stacks Chapter 4.
User-Defined Functions
Basic Elements of C++ Chapter 2.
Multiple Files Revisited
Corresponds with Chapter 5
Presentation transcript:

Computer Programming 1 Functions

Computer Programming 2 Objectives Take a first look at building functions Study how a function is called Investigate how a function executes Take a first look at class methods

Computer Programming 3 Problem Fahrenheit to Celsius Conversion Two scales used to measure temperature are the Fahrenheit and Celsius scales. A program is needed to convert temperatures in Fahrenheit to the equivalent Celsius temperatures. This program is suppose to be used in several other programs.

Computer Programming 4 Algorithm 1. Output a prompt for a Fahrenheit temperature to cout. 2. Input tempFahrenheit from cin. 3. Calculate tempCelsius = (tempFahrenheit – 32.0) / Output tempCelsius (and descriptive text) to cout.

Computer Programming 5 Functions The previous program cannot be used in other programs Real-world programs may contain thousands (or even millions) of lines of code. How can developers understand, develop, and maintain these monster programs? – Divide the program into chunks known as functions Functions are compact code units that can be used in other programs Written, inspected, and debugged without worrying about the code that surrounds them.

Computer Programming 6 Function Definitions Function declaration – function prototype – Gives the “full name” of the function to be called – Function prototype must precede any call or definition of a function - Compiler must know of a function's existence Else a compiler error will occur … undeclared Function definition – function implementation – Contains statements that specify its behavior when it is called. – Function must be defined in order to be called Else a linker error will occur undefined reference to …

Computer Programming 7 Syntax Declare a function – Usually, it is written in a specification file with.h extension ReturnType name (parameterDeclarations); Define a function – Usually, it is written in an implementation file with.cpp extension ReturnType name (parameterDeclarations) { //statements }

Computer Programming 8 Back to Fahrenheit To Celsius Conversion In a file named fahrCelConv.h const double scl=1.8; const double trn=32.0; double convertFahrToCel(double); In a file named fahrCelConv.cpp #include #include “fahrCelConv.h” using namesapce std; int main() { cout << convertFahrToCel(100.0); return 0; } double convertFahrToCel(double fahr) { return (fahr-trn)/scl; }

Computer Programming 9 Back to Fahrenheit To Celsius Conversion (without.h) In a file named fahrCelConv.cpp #include using namesapce std; double convertFahrToCel(double); int main() { cout << convertFahrToCel(100.0); return 0; } double convertFahrToCel(double fahr) { return (fahr-trn)/scl; } Note: Declaration is optional if the definition is given before calling the function

Computer Programming 10 Return type and name The return type can be any type – Primitive/basic types – User defined types Use void when the function does not return anything The rules for the names of functions are the same as for the variables Must start with a letter or underscore Use meaningful names

Computer Programming 11 Parameters Function variables for which the caller can specify values. Defined between the parentheses of a function’s definition. A function may not have parameters double fahrToCelsius(double tempFahr) { return (tempFahr ) / 1.8; } void do() { //statements }

Computer Programming 12 Arguments When a function is called – Caller can pass it values called arguments – Stored in the function’s parameters. double newTemp = convertFahToCel (212); double fahrToCelsius(double tempFahr) { return (tempFahr ) / 1.8; } The function then runs using its parameter values.

Computer Programming 13 How functions are called Recall: PC (program counter)/EIP (extended instruction pointer) – The register that holds the address of the next instruction to execute Call stack – Area of memory that holds information need for calling functions – A sequence of stack frames Each stack frame is associated with each function call

Computer Programming 14 Stack frames Each time a function is called, a new stack frame is created Each time a function is returned (done), the stack frame associated with it is eliminated ESP (extended stack pointer) holds the address of the top of the stack EBP (extended base pointers/frame pointer) is used to reference local variables and parameters inside the current stack frame

Computer Programming 15 Putting it all together Calling a function First the calling function pushes the parameters into the stack frame from R to L The EIP is then pushed into the stack, and points to the first instruction in the called function The old value of EBP is pushed into the stack frame Push the top of the stack into EBP Push the local variables into the stack – The local variables are not between EBP and ESP Save the old values of registers that are used by the called function

Computer Programming 16 Putting it all together Returning from function Restore the saved registers Release the storage for local variables Restore the old EBP Restore the old EIP (RET) – Go back to the calling function

Computer Programming 17 Design Specification of the function – Determines the form of the function heading Return value Name Parameters Algorithm of the function – Determines the content of the function body Input, Output Branching, looping

Computer Programming 18 Functions are subprograms A function can be viewed as a sub-program containing statements such as – Variable declarations and definitions – Selections and repetitions – Call to other functions The variables declared inside a function are called local variables – They are not visible to the code surrounding the function

Computer Programming 19 Problem Write a program that simulates a calculator with four menus. When the user presses S, the calculator computes the sum 1+…+n, where n is an integer entered by the user. When he presses F, the calculator computes the factorial of n (i.e. 1*2*…*n). If the user presses P, the calculator computes the p(n), Where p is a polynomial function give by p(x)=x 2 -5x *(x 2 -5x 5 ) 6 The number n is displayed as it is in all they other cases.

Computer Programming 20 Function inside a class Recall that a class is a new type that has attributes and operations – Attributes are the data that describe an object – Operations are for manipulating objects and their data An operation in a class is a function in that class. It is also known as class method (method) or a member function – A mechanism for building a new operation for a class type Two categories of methods – Class method: defines a message that can be sent to a class; the declaration/definition has static keyword – Instance method: defines a message sent to an object (an instance of a class); does not have static keyword

Computer Programming 21 Example on classes and methods A point in two dimension is determined by its x and y positions. Write a program that computes 1. The symmetric point of a point with respect to (0,0) 2. The distance of the point to (0,0) 3. The distance between two points The solution will be provided in the lecture

Computer Programming 22 Function inside a class class Person { private: string name; unsigned int id; public: Person (string n=“”, unsigned int x=0) { name = n; id = x; } string getName () { return name; } static string talk() { return "Salam!"; } }; Person bel = Person (“Belaid”, “27”); cout << bel.getName(); Cout << Person::talk(); //bel.talk()