Functions Why we use functions C library functions Creating our own functions.

Slides:



Advertisements
Similar presentations
Functions. COMP104 Functions / Slide 2 Introduction to Functions * A complex problem is often easier to solve by dividing it into several smaller parts,
Advertisements

Computer Programming w/ Eng. Applications
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Overview Reference parameters Documenting functions A game of craps. Design, code, test and document.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Overview creating your own functions calling your own functions.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 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.
Data Types, Expressions and Functions (part I)
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Agenda Review Compiling Review Data Types Integer Division Composition C++ Mathematical Functions User Input Reading: , 8.11 Homework #3.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
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.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
Chapter 3 Expressions and Interactivity Department of Computer Science Missouri State Univeristy.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Introduction As programmers, we don’t want to have to implement functions for every possible task we encounter. The Standard C library contains functions.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
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.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
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: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 ICS103 Programming in C Lecture 8: Functions I.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Introduction to Programming Lecture 6. Functions – Call by value – Call by reference Today's Lecture Includes.
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.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3: Expressions and Interactivity.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
Functions, Part 2 of 2 Topics Functions That Return a Value
Functions.
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Functions Declarations CSCI 230
Chapter 9 Scope, Lifetime, and More on Functions
6 Chapter Functions.
Chapter 6: User-Defined Functions I
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.
C Characters and Strings
Presentation transcript:

Functions Why we use functions C library functions Creating our own functions

Why functions average human mind can hold 6 things at once. (directions example) Construct a large program from smaller pieces or modules in C++ the pieces are called functions final program made up of library pieces plus pieces you write.

C Library Functions mathematical calculations sqrt, exp, log, sin, cos, tan, pow, etc. string manipulations strcat, strcpy, strcmp, strstr character manipulations isalpha, isdigit, islower, isupper, atol input/output cout, cin, printf, fopen, fclose, fwrite, fread memory allocation alloc, free searching and sorting bsearch (binary search), qsort (quick sort)

Invoking a library function Functions are called by writing the name of the function, followed by a left parentheses, followed by the argument list, followed by the right parentheses. For example: cout << sqrt (900.0); This code displays 30

Invoking a library function #include using namespace std; int main() { for (double i = 1; i <= 10; i++) { cout << "The square root of " << i << " is "; cout << sqrt (i) << endl; } return 0; }

Invoking a library function #include using namespace std; int main() { double squareRoot; for (double i = 1; i <= 10; i++) { cout << "The square root of " << i << " is "; squareRoot = sqrt (i) cout << squareRoot << endl; } return 0; }

Functions as black boxes sqrt y square root of y double

Function arguments constants double rootD1; rootd1 = sqrt ( ) ; variables double rootD1, d1 = 900.0; rootd1 = sqrt ( d1 ) ; expressions double rootD1, d1 = 900.0; rootd1 = sqrt ( d ) ;

More than one argument #include for (double i = 1; i <= 10; i++) { cout << i << " to the power of 10 is "; cout << pow (i, 10) << endl; } pow x (double) y (double) x to the power y (double)

Common programming error using a library function without reading the whole description For example: the pow library function description says “ pow does not recognize integral floating point values greater than 2 64, such as 1.0E100” A library function will explain it’s deficiences and limitations. Make sure you know what they are before using it!

Exercise - use abort instead #include // provides ifstream, ofstream #include // provides cout using namespace std; int main() { ifstream infile; infile.open("yards.in"); if (!infile) { cout << "Unable to open input file" << endl; cout << "Abnormal termination program" << endl; return 0; } return 0; }

Exercise - using rand write a code segment to generate and display 5 random numbers between 0 and assume srand has already been called with the current time to properly initialize the random generator

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 } function-name - any valid identifier. Our standard - verb, each word capitalized (GetInput) return-value-type - any valid data type, plus void void abort (); argument list - comma separated list of arguments. Each must have a data type. Okay if function has no arguments. bool IsEmpty();

Example - Square function 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

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; }

Returning control to caller - no return value void DisplayErrorMessage(string errorMessage) { cout << errorMessage << endl; } or void DisplayErrorMessage(string errorMessage) { cout << errorMessage << endl; return ; }

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

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 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; }