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

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

C++ Programming Lecture 11 Functions Part I

Chapter 6 - Notes User-Defined Functions I

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

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

COMP 111 PROGRAMMING I MODULARITY USING FUNCTIONS

Programming Language. Functions. Eng. Anis Nazer First Semester

Functions. Lecture 6 COP 3014 Spring February 11, 2018

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

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

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

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

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

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

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

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

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

Lecture 04 FUNCTIONS AND ARRAYS

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

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

C++ Programming: Functions

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

4. C++ functions. 1. Library Function 2. User-defined Function

Companion C++ Examples

Summary of basic C++-commands

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

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

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.

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

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

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

Using Free Functions

Engineering Problem Solving with C++, Etter/Ingber

cast.c /* Program illustrates the use of a cast to coerce a function argument to be of the correct form. */

Chapter 4 Computer Science with C++ Name: Review Worksheet A Mr. Ferwerda

From Pseudcode Algorithms directly to C++ programs

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

Chapter 2. Outline. Simple C++ Programs

Introduction to Programming

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

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

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

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

Chapter 7 - Notes User-Defined Functions II

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Chapter 3. Numeric Types, Expressions, and Output

CT 229 Java Syntax Continued

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

Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

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

Chapter 4: Basic C Operators

BITG 1113: Function (Part 2) LECTURE 5

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

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

More loops Ch

Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

Fundamentals of Programming & Procedural Programming

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

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

Functions and Recursion

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

CS201 Latest Solved MCQs

Elements of C in C++ data types if else statement for loops. random numbers rolling a die

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

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

Getting started with C++ (Part 2)

Programming. C++ Basics

C Program Structures

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

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

ANSI C Programming Simple Programs

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

C Functions. 5.2 Program Modules in C

CS Spring 05 - MidTerm

Introduction to C++ Introduction to C++ 1

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

A SHORT COURSE ON C++

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Part II Answer to all the questions (2 Marks):

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

Chapter 3 - Functions

Introduction to Computer Science Midterm 3 Fall, Points

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

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

Fundamentals of Programming. Lecture 19 Hamed Rasifard

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

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 (!

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Programming in C++ The manager of a company. Lecture Notes 6. Functions (Procedures) 4/24/2018. he he he. Does Does Does

Functions. Systems Programming Concepts

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

CS2141 Software Development using C/C++ C++ Basics

CSCE Practice Midterm. Data Types

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

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

C Programming for Engineers Functions

case control statement (switch case)

Transcription:

Outline Functions Predefined functions User-defined functions Actual parameters Formal parameters Value parameters Variable parameters Functions 1 Functions 2 Functions Predefined Functions In C++ there are two types of functions, predefined functions and user-defined functions. Predefined functions come with libraries of C++. User-defined functions are created by programmers. Function Name Type of Arguments Type of Value Returned Purpose pow(x,y) double double x y sqrt(x) double double square root of x abs(x) int int x fabs(x) double double x floor(x) double double largest integer n x ceil(x) double double smallest integer o x Functions 3 Functions 4 To use predefined functions, the user should know the argument type and the return type of that function. For instance, square root function sqrt(x) has double as argument type and double as return type. This means if the user wants to find the square root of 16 and assign it to the variable named Root. The user should declare Root as type double as follows: double Root; Root = sqrt(16.0); The expression sqrt(16.0)is called a function call, and it returns the value of 4.0. This value 4.0 is then assigned to Root. Functions 5 Functions 6 1

User-Defined Functions A user-defined function provides us a way to break down a complex program into subprograms. These subprograms are easier to design and understand. we want to write a function that will determine a letter grade from the given average score. In general, the average score can be obtained from different methods depend upon the given raw scores, e.g. 3 test scores and a final score or 2 test scores, quiz scores, and a final score. Functions 7 Functions 8 This implies that we have to write two different programs to assign a letter grade for each problem. It will be useful if we have a function to determine a letter grade to use regardless of the raw scores. This means we only have to write a program to compute the average and call the function that determines the letter grade. Functions 9 #include <iostream> #include <math> char AssignGrade(int); // Function prototype int main (void) int Test1, Test2, Test3, Final; int NormalizeScore; double Score; char FinalGrade; cin>>test1>>test2>>test3>>final; Score = (Test1+Test2+Test3+Final)/4.0; NormalizeScore = ceil(score); NormalizeScore = (NormalizeScore / 10) * 10; FinalGrade = AssignGrade(NormalizeScore); cout<<"your grade is "<<FinalGrade; return 0; } //main Functions 10 char AssignGrade (int Score) /* Pre-condition: Score is an integer. Post-condition: The value returned is a letter grade corresponding to char Grade; switch (Score) } case 100: case 90: the Score. */ Grade = 'A'; case 80: Grade = 'B'; case 70: Grade = 'C'; case 60: Grade = 'D'; default: Grade = 'F'; return Grade; } //AssignGrade Functions 11 Structure of Functions There are 2 main steps to create user-defined functions besides main function. Function prototype Function definition: Function definition consists of two parts Function header Body of the function Functions 12 2

Function Prototype This similar to declaring an identifier. This part is to announce that there is/are other function/functions in the program besides main function. Function prototype comes between header files and main function. Function Prototype The structure of function prototype is as follows: return type function name (list of formal-parameter types) char AssignGrade(int); double AreaOfRectangle(double,double); double Power(double Base, int ; Functions 13 Functions 14 Function Definition #include <iostream.h> #include <math.h> Char AssignGrade(int);//Function prototype int main (void) } //main char AssignGrade (int Score)//Function header /* Pre-condition: Score is an integer. Post-condition: The value returned is a letter grade corresponding to the Score. */ //Beginning of the body of AssignGrade function char Grade; switch (Score) } return Grade; } //The end of the body of AssignGrade function Functions 15 Functions 16 double AreaOfRectangle(double Width,double Length) //Function header /* Pre-condition: Width and Length of the rectangle. Post-condition: The value returned is the area of the rectangle. */ //Beginning of the body of AreaOfRectagle function return Width * Length; } //The end of the body of AreaOfRectangle function Functions 17 double Power(double Base, int //Function header /* Pre-condition: Base and Exponent. Post-condition: The value returned is Base^Exponent. */ //Beginning of the body of Power function double Product = 1; int AbsExponent, Count; if (Exponent > 0) for (Count = 1;Count <= Exponent; Count++) Product = Product * Base; else if (Exponent < 0) for (Count = 1;Count <= abs(;count++) } else Product = Product * Base; Product = 1 / Product; Product = 1; return Product; } //The end of the body of Power function Functions 18 3

Function Parameters Actual parameters are parameters in function call, e.g., NormalizeScore. FinalGrade = AssignGrade(NormalizeScore); Formal parameters are parameters declared in the function header, e.g., Score, Width, Length, Base, and Exponent. Function Parameters Note that the return type and the list of formal parameters of a function can be void. This means the function returns nothing if the return type is void, and there is no formal parameter if the list of formal parameters is void. Functions 19 Functions 20 Formal Parameters Value Parameters There are 2 types of formal parameters: Value parameters Variable parameters A value parameter is a formal parameter that receives a copy of the contents of the corresponding actual parameter. This means the value of the actual parameter is independent from the value of the formal parameter. Functions 21 Functions 22 of Value Parameters For example, a function call ExpVal = Power(MainBase, Exp); Where MainBase and Exp are actual parameter. The function definition (heading) is double Power(double Base, int of Value Parameters Base and Exponent are formal parameter. When the function call in the main function is executed, temporary memory locations for Base and Exponent are established. Then a copy of the content of Mainbase and Exp are made as content of Base and Exponent, respectively. Functions 23 Functions 24 4

Variable Parameters A variable parameter is a formal parameter that receives the memory location of the corresponding actual parameter. This means the value of the actual parameter will change if the value of the formal parameter changes. Functions 25 Functions 26 Variable Parameters Variable Parameters For example, a function call ExpVal = Power(MainBase, Exp); Where MainBase and Exp are actual parameter. The function definition (heading) is double Power(double& Base, int Base and Exponent are formal parameters. When the function call in the main function is executed, a connection for variable parameter Base to memory locations of MainBase is established. The temporary memory location for Exponent is also established and a copy of the content of Exp is made as content Exponent. Functions 27 Functions 28 void FindAverage(double& Average) //Function header /* Pre-condition: None. Post-condition: The value returned is an average of scores. */ //Beginning of the body of FinAverage function int Test1, Test2, Test3, Final; cout >> "Enter three test scores and a final score"; cin << Test1<<Test2<<Test3<<Final; Average = (Test1+Test2+Test3+Final)/4.0 } //The end of the body of FindAverage function Functions 29 Functions 30 5

Caution One must be very careful to make a function call when one or more formal parameters of the function to be called are variable formal parameters. Caution The actual parameters in the function call must be identifier (variable) names. They cannot be expression. For example, the function Power double Power(double& Base, int A function call ExpVal = Power(MainBase, Exp); is a correct call. But ExpVal = Power(2.0, Exp); will produce compilation error. Functions 31 Functions 32 Value Parameters Value Parameters For value formal parameters, the actual parameters can be any type of expressions since their contents do not change. For example, the function Power double Power(double Base, int The followings are valid function calls: ExpVal = Power(MainBase,Exp); ExpVal = Power(2.0,5); ExpVal = Power(2.0*MainBase,5); ExpVal = Power(2.0*3,Exp); ExpVal = Power(MainBase,4*Exp); Functions 33 Functions 34 Type of Variables Local variables: A local variable is an identifier declared in a function. Local variables can only be accessed in side its own function. Global variables: A global variable is an identifier declared outside of any functions. Global variables can be accessed by any functions. #include <iostream.h> #include <math.h> char AssignGrade(int); // Function prototype int main (void) int Test1, Test2, Test3, Final; int NormalizeScore; double Score; char FinalGrade; return 0; } //main Functions 35 Functions 36 6

char AssignGrade (int Score) /* Pre-condition: Score is an integer. Post-condition: The value returned is a letter grade corresponding to the Score. */ char Grade; return Grade; } //AssignGrade Test1, Test2, Test3, Final, NormalizeScore, Score, FinalGrade are local variables of function main. Grade is a local variable of function AssignGrade. Functions 37 7