Overview creating your own functions calling your own functions.

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

1 Programming in C++ Lecture Notes 9 Functions (Returning Values) Andreas Savva.
Overview Reference parameters Documenting functions A game of craps. Design, code, test and document.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 5. Functions.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Functions A function is a snippet of code that performs a specific task or tasks. You use a multitude of functions daily when you do such things as store.
Chapter 7 Functions.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
1 Lecture 3 Part 1 Functions with math and randomness.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 Programming in C++ Dale/Weems/Headington Chapter 7 Functions.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
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.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
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.
Functions Why we use functions C library functions Creating our own functions.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task.
Unit 3 Lesson 11 Passing Data and Using Library Functions Textbook Authors: Knowlton, Barksdale, Turner, & Collings PowerPoint Lecture by Dave Clausen.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
 In this chapter you ‘’ll learn: ◦ To construct programs modularly from functions ◦ To use common math library functions ◦ The mechanism for passing.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals Enumerations and Functions.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Dale Roberts CSCI N305 Functions Declarations Department of Computer and Information Science, School of Science, IUPUI.
A Sample Program #include using namespace std; int main(void) { cout
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
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.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
C++ Lesson 1.
Suppose we want to print out the word MISSISSIPPI in big letters.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 9 Scope, Lifetime, and More on Functions
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
6 Chapter Functions.
Chapter 6: User-Defined Functions I
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Fundamental Programming
Functions Imran Rashid CTO at ManiWeber Technologies.
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
Presentation transcript:

Overview creating your own functions calling your own functions

function definition return-value-type function-name (argument list) { declarations and statements } Example: int Square (int y) { int result; result = y * y; return result; }

function definition return-value-type function-name (argument list) { declarations and statements } return-value-type - any valid data type, plus void void abort () double sqrt (double) int main () function-name - any valid identifier. Our standard - verb, each word capitalized GetInput IsValid ShowMessage

function definition return-value-type function-name (argument list) { declarations and statements } argument list - comma separated list of arguments. Each must have a data type. Okay if function has no arguments. bool IsEmpty() bool IsEmpty(void) double sqrt (double x) double pow( double x, double y ) Each argument is a declaration. (See square example)

Returning control to caller - no return value void DisplayErrorMessage(int errorNumber) { cout << “Error Message number is “ << errorNumber; } or void DisplayErrorMessage(int errorNumber) { cout << “Error Message number is “ << errorNumber; return ; }

Returning control to caller with return value bool IsEmpty() { if (0 == bufferCount ) return true; else return false; }

Exercises 1) write a function which accepts an integer value as input, and returns an integer which is the cube of that input. Cube y 3 y int 2) write a function that accepts a char as input and returns true if the char is a digit from 0 to 9 or false if the character is not a digit from 0 to 9. IsDigit bool true if ch is 0 to 9 false if ch is not 0 to 9 ch char int

calling a function int main() { Function1 (); return 0; } void Function1() { return; }

function flow of control int main() { cout << “About to call Function1” << endl; Function1 (); cout << “Returned from Function1” << endl; return 0; } void Function1() { cout << “Inside Function1” << endl; return; } Demonstrate this

function flow of control - 2 calls int main() { cout << “About to call Function1” << endl; Function1 (); cout << “Returned from Function1” << endl; cout << “calling Function1 again” << endl; Function1 (); cout << “Returned from calling Function1 again” << endl; return 0; } void Function1() { cout << “Inside Function1” << endl; return; } Demonstrate this

benefits of functions Function code implemented once. Changes happen in one place main routine easier to understand because details of Function1 removed. When writing main routine only have to think about main. When writing Function1 only have to think about Function1

cout statements as a debug technique can determine flow of control can determine how and when variables change.

Inputs and outputs int main () { int xSquared, int x = 10; xSquared = Square (x); cout << “ the square of “ << x << “ is “ << xSquared; return 0; } int Square (int y) { int result; result = y * y; return result; } What happens to xSquared, x, y, result? Walk through. Show memory

variables inside a function are not visible outside the function int main () { int xSquared; for (int x = 1; x <= 10; x++) { xSquared = Square (x); cout << xSquared << “ “ ; } cout << result; // would cause a compiler error return 0; } int Square (int y) { int result; result = y * y; return result; }

y is not visible outside the function int main () { int xSquared; for (int x = 1; x <= 10; x++) { xSquared = Square (x); cout << xSquared << “ “ ; } cout << y; // would cause a compiler error return 0; } int Square (int y) { int result; result = y * y; return result; }

Exercises 1) Write a main function which calls the Cube function that you wrote earlier. Have it calculate the cube of the numbers from 1 to 10 and display them. int Cube (int y) 2) Write a main function which calls the IsDigit function that you wrote earlier. Have it read in 10 input characters from a user and for each one, display whether it is a digit or not. bool IsDigit (char ch)

function prototype Tells compiler: type of data returned from function number of arguments function expects to receive type of arguments the function expects to receive order in which those arguments are expected. Example: int Square (int y);

function prototype Compiler must see either the function itself or the function prototype before the function is actually called in the code. int Square (int y); int main () { int xSquared; for (int x = 1; x <= 10; x++) { xSquared = Square (x); cout << xSquared << “ “ ; } return 0; } Function itself may be in a different file as it is with library functions

Area of a Triangle AreaTriangle side1 side2 side3 (float) area of the triangle (float)

#include using namespace std; float AreaTriangle (float side1, float side2, float side3); // prototype int main () { float a, b, c; // the three sides of the triangle float area; float area; cout << endl << "This program calculates the area of a triangle"; cout << endl << "with sides of length 3.0, 4.0, and 5.0" << endl; a = 3.0; b = 4.0; c = 5.0; area = AreaTriangle(a, b, c); cout << endl << "The area of the triangle is " << area << endl; return 0; } /* * PRE: side1, side2, and side3 are positive numbers that * form the sides of a triangle * POST: returns the area of a triangle with sides side1, * side2, side3 */ float AreaTriangle (float side1, float side2, float side3) { float s; // local variable - the semiperimiter s = (side1 + side2 + side3) / 2.0; return (sqrt ( s * (s - side1) * (s - side2) * (s - side3) ) ); }

variables s side3 side2 side1 area c b a s, side1, side2, side3 are variables in the AreaTriangle function area, a, b and c are variables in the main program At runtime a copy of a, b, c is made and used to initialize side1, side2 and side3

miscellaneous you could skip writing a prototype all together and just put the function ahead of main. Not intuitive. Makes source code hard to read. you could implement AreaTriangle initially as a stub with no other code except return 0;

1) Write a function named Smallest that takes three integer inputs and returns an integer that is the smallest of the three inputs. Write the prototype for the Smallest function. Write a program that gets 3 integers from a user and displays the smallest 2) Write a function that, given a letter of the alphabet, returns true if the letter is a vowel (lower or uppercase) and returns false if the letter is not a vowel. IsAVowel true if letter is a vowel false if letter is not a vowel letter (char) 3) Write the prototype for IsAVowel. Write a program to invoke the IsAVowel function. Inputs a letter and prints out whether it is or is not a vowel.

Automatic conversions What if the parameter you want to send is different than that expected by the function? double Square (double y); int main () { double xSquared; for (int x = 1; x <= 10; x++) { xSquared = Square (x); cout << xSquared << “ “ ; } return 0; } x converted to double. Works fine.

Automatic conversions What if the parameter you want to send is different than that expected by the function? int Square (int y); int main () { double d1 = 9.8; cout << Square (d1); // displays 81 return 0; return 0; } d1 converted to int. Information is lost. Beware!

Promotion rules Specify which types can be converted to other types without losing data. As long as you follow the promotion rules then conversions are okay. Must promote to a data type higher in the hierarchy

Promotion hierarchy long double double float unsigned long int long int unsigned int int unsigned short int short int unsigned char char

Common programming error Losing data by allowing the compiler to change a data type and not follow the promotion rules.

Exercises 1) Find the error in each of the following program segments and explain how to fix it. a) int sum (int x, int y) { int result; result = x + y; } b) int sum (int n) { if (0 == n) return 0; else n = n + n; } c) in main program: double x = 1E10; cout << "square of 1E10 = " << square (x) << endl; int square (int x) { return x * x; }

More Exercises 1) Find the error in the following function and fix it. void displayErrorMessage (int errorNumber) { switch (errorNumber) { case 0: cout << "Fatal Error!" << endl; break; case 1: cout << "Error!" << endl; break; default: cout << "Invalid error code" << endl; } return true; }