Functions How to reuse code.

Slides:



Advertisements
Similar presentations
Local and Global Variables. COMP104 Local and Global / Slide 2 Scope The scope of a declaration is the block of code where the identifier is valid for.
Advertisements

Chapter 5 Functions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 5 Function Basics.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
Function Part II: Some ‘advanced’ concepts on functions.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
CS 1400 Chap 6 Functions. Library routines are functions! root = sqrt (a); power = pow (b, c); function name argument arguments.
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 7 Functions.
Call-by-Value vs. Call-by-Reference Call-by-value parameters are used for passing information from the calling function to the called function (input parameters).
CSC 107 – Programming For Science. Today’s Goal  Discuss writing & using functions  How to declare them, use them, & trace them  Could write programs.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
CPS120: Introduction to Computer Science Functions.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
CPS120: Introduction to Computer Science Lecture 14 Functions.
111/15/2015CS150 Introduction to Computer Science 1 Summary  Exam: Friday, October 17,  Assignment: Wednesday, October 15, 2003  We have completed.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
1 10/18/04CS150 Introduction to Computer Science 1 Functions Divide and Conquer.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Simple Functions Writing Reuseable Formulas. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
CSE 1341 Honors Note Set 2 1. Overview  Java vs. C++  Functions in C++  First Programming Packet  Development Environment 2.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
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.
User-Written Functions
Chapter 6: User-Defined Functions I
C++ Templates.
Bill Tucker Austin Community College COSC 1315
Chapter 5 Function Basics
Chapter 5 Function Basics
Chapter 5 Functions.
CMPT 201 Functions.
Pointers and Pointer-Based Strings
Writing Reuseable Formulas
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
Chapter 6: Functions Starting Out with C++ Early Objects
User-defined Functions
Functions Inputs Output
CSC1201: Programming Language 2
Exceptions with Functions
Chapter 5 Function Basics
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.
User-defined Functions
More ‘concepts’ on Function
C++ Compilation Model C++ is a compiled language
Chapter 6: User-Defined Functions I
Functions Divide and Conquer
Pointers and Pointer-Based Strings
Fundamental Programming
CSC1201: Programming Language 2
Separate Compilation.
Functions Imran Rashid CTO at ManiWeber Technologies.
Chapter 8 Functions.
CS1201: Programming Language 2
Instructor: Hidayah Elias Course: COMPUTER PROGRAMMING (BFC 2042)
CPS125.
More ‘concepts’ on Function
Presentation transcript:

Functions How to reuse code

#include <iostream> using namespace std; int main() { int threeExpFour = 1; for (int i = 0; i < 4; i = i + 1) { threeExpFour = threeExpFour * 3; } cout << "3^4 is " << threeExpFour << endl; return 0;

#include <iostream> using namespace std; Copy-paste coding int main() { int threeExpFour = 1; for (int i = 0; i < 4; i = i + 1) { threeExpFour = threeExpFour * 3; } cout << "3^4 is " << threeExpFour << endl; int sixExpFive = 1; for (int i = 0; i < 5; i = i + 1) { sixExpFive = sixExpFive * 6; cout << "6^5 is " << sixExpFive << endl; return 0;

#include <iostream> using namespace std; Copy-paste coding (bad) int main() { int threeExpFour = 1; for (int i = 0; i < 4; i = i + 1) { threeExpFour = threeExpFour * 3; } cout << "3^4 is " << threeExpFour << endl; int sixExpFive = 1; for (int i = 0; i < 5; i = i + 1) { sixExpFive = sixExpFive * 6; cout << "6^5 is " << sixExpFive << endl; int twelveExpTen = 1; for (int i = 0; i < 10; i = i + 1) { twelveExpTen = twelveExpTen * 12; cout << "12^10 is " << twelveExpTen << endl; return 0;

With a function #include <iostream> using namespace std; // some code which raises an arbitrary integer // to an arbitrary power int main() { int threeExpFour = raiseToPower(3, 4); cout << "3^4 is " << threeExpFour << endl; return 0; }

With a function #include <iostream> using namespace std; // some code which raises an arbitrary integer // to an arbitrary power int main() { int threeExpFour = raiseToPower(3, 4); cout << "3^4 is " << threeExpFour << endl; int sixExpFive = raiseToPower(6, 5); cout << "6^5 is " << sixExpFive << endl; return 0; }

With a function #include <iostream> using namespace std; // some code which raises an arbitrary integer // to an arbitrary power int main() { int threeExpFour = raiseToPower(3, 4); cout << "3^4 is " << threeExpFour << endl; int sixExpFive = raiseToPower(6, 5); cout << "6^5 is " << sixExpFive << endl; int twelveExpTen = raiseToPower(12, 10); cout << "12^10 is " << twelveExpTen << endl; return 0; }

Why define your own functions? Readability: sqrt(5) is clearer than copy-pasting in an algorithm to compute the square root Maintainability: To change the algorithm, just change the function (vs changing it everywhere you ever used it) Code reuse: Lets other people use algorithms you’ve implemented

Function Declaration Syntax Function name int raiseToPower(int base, int exponent) { int result = 1; for (int i = 0; i < exponent; i = i + 1) { result = result * base; } return result;

Function Declaration Syntax Return type int raiseToPower(int base, int exponent) { int result = 1; for (int i = 0; i < exponent; i = i + 1) { result = result * base; } return result;

Function Declaration Syntax Argument 1 int raiseToPower(int base, int exponent) { int result = 1; for (int i = 0; i < exponent; i = i + 1) { result = result * base; } return result; Argument order matters: raiseToPower(2,3) is 2^3=8 raiseToPower(3,2) is 3^2=9

Function Declaration Syntax Argument 2 int raiseToPower(int base, int exponent) { int result = 1; for (int i = 0; i < exponent; i = i + 1) { result = result * base; } return result; Argument order matters: raiseToPower(2,3) is 2^3=8 raiseToPower(3,2) is 3^2=9

Function Declaration Syntax int raiseToPower(int base, int exponent) { int result = 1; for (int i = 0; i < exponent; i = i + 1) { result = result * base; } return result; signature

Function Declaration Syntax int raiseToPower(int base, int exponent) { int result = 1; for (int i = 0; i < exponent; i = i + 1) { result = result * base; } return result; body

Function Declaration Syntax int raiseToPower(int base, int exponent) { int result = 1; for (int i = 0; i < exponent; i = i + 1) { result = result * base; } return result; Return statement

#include <iostream> using namespace std; Function declaration int raiseToPower(int base, int exponent) { int result = 1; for (int i = 0; i < exponent; i = i + 1) { result = result * base; } return result; } Function invocation int main() { int threeExpFour = raiseToPower(3, 4); cout << "3^4 is " << threeExpFour << endl; return 0; }

Returning a value Up to one value may be returned; it must be the same type as the return type. int foo() char* foo() { return "hello"; // error return "hello"; // ok }

Returning a value Up to one value may be returned; it must be the same type as the return type. If no values are returned, give the function a void return type void printNumber(int num) { cout << "number is " << num << endl; } int main() { printNumber(4); // number is 4 return 0;

Returning a value Up to one value may be returned; it must be the same type as the return type. If no values are returned, give the function a void return type – Note that you cannot declare a variable of type void int main() { void x; // ERROR return 0; }

Returning a value Return statements don’t necessarily need to be at the end. Function returns as soon as a return statement is executed. void printNumberIfEven(int num) { if (num % 2 == 1) { cout << "odd number" << endl; return; } cout << "even number; number is " << num << endl; int main() { int x = 4; printNumberIfEven(x); // even number; number is 3 int y = 5; printNumberIfEven(y); // odd number

cout << x << endl; Argument Type Matters void printOnNewLine(int x) { cout << x << endl; } printOnNewLine(3) works printOnNewLine("hello") will not compile

Argument Type Matters printOnNewLine(3) will not compile void printOnNewLine(char *x) { cout << x << endl; } printOnNewLine(3) will not compile printOnNewLine("hello") works

cout << x << endl; Argument Type Matters void printOnNewLine(int x) { cout << x << endl; } void printOnNewLine(char *x) printOnNewLine(3) works printOnNewLine("hello") also works

Function declarations need to occur before invocations int foo() { return bar()*2; // ERROR - bar hasn’t been declared yet } int bar() return 3;

Function declarations need to occur before invocations – Solution 1: reorder function declarations int bar() { return 3; } int foo() return bar()*2; // ok

Function declarations need to occur before invocations Solution 1: reorder function declarations Solution 2: use a function prototype; informs the compiler you’ll implement it later int bar(); function prototype int foo() { return bar()*2; // ok } int bar() return 3;

Function prototypes should match the signature of the method, though argument names don’t matter int square(int); function prototype int cube(int x) { return x*square(x); } int square(int x) return x*x;

Function prototypes should match the signature of the method, though argument names don’t matter int square(int x); function prototype int cube(int x) { return x*square(x); } int square(int x) return x*x;

Function prototypes should match the signature of the method, though argument names don’t matter int square(int z); function prototype int cube(int x) { return x*square(x); } int square(int x) return x*x;

Function prototypes are generally put into separate header files – Separates specification of the function from its implementation // myLib.h - header // contains prototypes // myLib.cpp - implementation #include "myLib.h" int square(int); int cube (int); int cube(int x) { return x*square(x); } int square(int x) { return x*x; }

Global Variables How many times is function foo() called? Use a global variable to determine this. – Can be accessed from any function int numCalls = 0; Global variable void foo() { ++numCalls; } int main() { foo(); foo(); foo(); cout << numCalls << endl; // 3

int numCalls = 0; Scope int raiseToPower(int base, int exponent) { numCalls = numCalls + 1; int result = 1; for (int i = 0; i < exponent; i = i + 1) { result = result * base; Scope: where a variable was declared, determines where it can be accessed from } } return result; numCalls has global scope – can be accessed from any function result has function scope – each function can have its own separate variable named result int max(int num1, int num2) { numCalls = numCalls + 1; int result; if (num1 > num2) { result = num1; } else { result = num2; return result;

Pass by value vs by reference So far we’ve been passing everything by value – makes a copy of the variable; changes to the variable within the function don’t occur outside the function // pass-by-value void increment(int a) { a = a + 1; cout << "a in increment " << a << endl; } Output int main() { int q = 3; increment(q); // does nothing cout << "q in main " << q << endl; } a in increment 4 q in main 3

Pass by value vs by reference main function scope q=3 // pass-by-value void increment(int a) { a = a + 1; cout << "a in increment " << a << endl; } Output int main() { int q = 3; // HERE increment(q); // does nothing cout << "q in main " << q << endl; } a in increment 4 q in main 3

Pass by value vs by reference main function scope increment function scope q=3 a=3 // pass-by-value void increment(int a) { // HERE a = a + 1; cout << "a in increment " << a << endl; } Output int main() { int q = 3; increment(q); // does nothing cout << "q in main " << q << endl; } a in increment 4 q in main 3

Pass by value vs by reference main function scope increment function scope q=3 a=4 // pass-by-value void increment(int a) { a = a + 1; // HERE cout << "a in increment " << a << endl; } Output int main() { int q = 3; increment(q); // does nothing cout << "q in main " << q << endl; } a in increment 4 q in main 3

Pass by value vs by reference If you want to modify the original variable as opposed to making a copy, pass the variable by reference (int &a instead of int a) // pass-by-value void increment(int &a) { a = a + 1; cout << "a in increment " << a << endl; } Output int main() { int q = 3; increment(q); // works cout << "q in main " << q << endl; } a in increment 4 q in main 4

Pass by value vs by reference main function scope q=3 // pass-by-value void increment(int &a) { a = a + 1; cout << "a in increment " << a << endl; } Output int main() { int q = 3; // HERE increment(q); // works cout << "q in main " << q << endl; } a in increment 4 q in main 4

Pass by value vs by reference main function scope increment function scope q=3 a // pass-by-value void increment(int &a) { // HERE a = a + 1; cout << "a in increment " << a << endl; } Output int main() { int q = 3; increment(q); // works cout << "q in main " << q << endl; } a in increment 4 q in main 4

Pass by value vs by reference main function scope increment function scope q=4 a // pass-by-value void increment(int &a) { a = a + 1; // HERE cout << "a in increment " << a << endl; } Output int main() { int q = 3; increment(q); // works cout << "q in main " << q << endl; } a in increment 4 q in main 4

Implementing Swap void swap(int &a, int &b) { int t = a; a = b; b = t; } int main() { int q = 3; int r = 5; swap(q, r); cout << "q " << q << endl; // q 5 cout << "r " r << endl; // r 3 }

Implementing Swap void swap(int &a, int &b) { int t = a; a = b; b = t; } int main() { int q = 3; int r = 5; // HERE swap(q, r); cout << "q " << q << endl; // q 5 cout << "r " << r << endl; // r 3 main function scope q=3 r=5

Implementing Swap void swap(int &a, int &b) { // HERE int t = a; a = b; b = t; } main function scope q=3 r=5 int main() { int q = 3; int r = 5; swap(q, r); cout << "q " << q << endl; // 5 cout << "r r 3 } swap function scope a b

Implementing Swap void swap(int &a, int &b) { main function scope int t = a; // HERE a = b; b = t; } int main() { int q = 3; int r = 5; swap(q, r); cout << "q " << q << endl; // q 5 cout << "r " << r << endl; // r 3 main function scope q=3 r=5 swap function scope a b t=3

Implementing Swap void swap(int &a, int &b) { main function scope int t = a; a = b; // HERE b = t; } int main() { int q = 3; int r = 5; swap(q, r); cout << "q " << q << endl; // q 5 cout << "r " << r << endl; // r 3 main function scope q=5 r=5 swap function scope a b t=3

Implementing Swap void swap(int &a, int &b) { main function scope int t = a; a = b; b = t; // HERE } int main() { int q = 3; int r = 5; swap(q, r); cout << "q " << q << endl; // q 5 cout << "r " << r << endl; // r 3 main function scope q=5 r=3 swap function scope a b t=3

Returning multiple values The return statement only allows you to return 1 value. Passing output variables by reference overcomes this limitation. int divide(int numerator, int denominator, int &remainder) { remainder = numerator % denominator; return numerator / denominator; } int main() { int num = 14; int den = 4; int rem; int result = divide(num, den, rem); cout << result << "*" << den << "+" << rem << "=" << num << endl; // 3*4+2=12 }

Libraries Libraries are generally distributed as the header file containing the prototypes, and a binary .dll/.so file containing the (compiled) implementation – Don’t need to share your .cpp code // myLib.h – header // contains prototypes double squareRoot(double num); myLib.dll

Library user only needs to know the function prototypes (in the header file), not the implementation source code (in the .cpp file) – The Linker (part of the compiler) takes care of locating the implementation of functions in the .dll file at compile time // myLib.h – header // contains prototypes double squareRoot(double num); myLib.dll // libraryUser.cpp – some other guy’s code #include "myLib.h" double fourthRoot(double num) { return squareRoot(squareRoot(num)); }

Final Notes You don’t actually need to implement raiseToPower and squareRoot yourself; cmath (part of the standard library) contains functions pow and sqrt #include <cmath> double fourthRoot(double num) { return sqrt(sqrt(num)); }

Array passing C++ Program to display marks of 5 students by passing one-dimensional array to a function. #include <iostream> using namespace std; void display(int marks[5]); int main() { int marks[5] = {88, 76, 90, 61, 69}; display(marks); return 0; }

Array passing void display(int m[5]) { cout << "Displaying marks: "<< endl; for (int i = 0; i < 5; ++i) cout << "Student "<< i + 1 <<": "<< m[i] << endl; } Output Displaying marks: Student 1: 88 Student 2: 76 Student 3: 90 Student 4: 61 Student 5: 69