Functions. Functions in C++ Calling a function? What you should know? Function return types. Parameter Type-Checking. Defining a function

Similar documents
CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Computer Science II Lecture 2 Strings, Vectors and Recursion

Lecture on pointers, references, and arrays and vectors

Functions and Recursion

C Functions. Object created and destroyed within its block auto: default for local variables

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Recursion. Recursion is: Recursion splits a problem:

Function Templates. Consider the following function:

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Arrays. Week 4. Assylbek Jumagaliyev

15. Pointers, Algorithms, Iterators and Containers II

Informatik I (D-ITET) Übungsstunde 9, Hossein Shafagh

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

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Working with Batches of Data

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Scientific Computing

Introduction to C++ Introduction to C++ 1

Recursion Examples. Factorial Recursive: Factorial Iterative: #include <iostream> using namespace std; long fact(long n) { if (n == 1) return 1;

Fast Introduction to Object Oriented Programming and C++

CS

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Introduction to C++ Systems Programming

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Exercise 9 Pointers, Iterators and Recursion

Short Notes of CS201

Chapter 3 - Functions

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

CS201 - Introduction to Programming Glossary By

An introduction to. Templates. Generic Programming. Good old C. Metaprogramming 4/13/2017

Suppose that you want to use two libraries with a bunch of useful classes and functions, but some names collide:

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

1 #include <iostream > 3 using std::cout; 4 using std::cin; 5 using std::endl; 7 int main(){ 8 int x=21; 9 int y=22; 10 int z=5; 12 cout << (x/y%z+4);

COMP6771 Advanced C++ Programming

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Chapter 3 - Functions

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

CS302 - Data Structures using C++

Intermediate Programming, Spring 2017*

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

CS242 COMPUTER PROGRAMMING

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

UEE1303(1070) S12: Object-Oriented Programming Operator Overloading and Function Overloading

Chapter 3 - Functions

To explain growth rates and why constants and nondominating terms can be ignored in the estimation

Operators. The Arrow Operator. The sizeof Operator

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

PHY4321 Summary Notes

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

Programmazione. Prof. Marco Bertini

Functions. Arizona State University 1

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

CSCI 111 Midterm 1, version A Exam Fall Solutions 09.00am 09.50am, Tuesday, October 13, 2015

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself.

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt

UEE1303(1070) S12: Object-Oriented Programming Advanced Topics of Class

Exercise 1.1 Hello world

4. Functions. March 10, 2010

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017

Recursion. ! When the initial copy finishes executing, it returns to the part of the program that made the initial call to the function.

Submit your answers to these questions to the Curator under Quizzes as HW08 by the posted due date and time. No late submissions will be accepted.

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

CMSC 202 Midterm Exam 1 Fall 2015

Templates. Zoltán Porkoláb: C++11/14 1

Introduction to Programming

COEN244: Class & function templates

EECS402 Lecture 02. Functions. Function Prototype

Pointers, Dynamic Data, and Reference Types

Programming in C++: Assignment Week 8

Standard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing

Communication With the Outside World

Chapter-13 USER DEFINED FUNCTIONS

Introduction to C ++

Introduction to C++ (Extensions to C)

Lab Instructor : Jean Lai

Topics. bool and string types input/output library functions comments memory allocation templates classes

Abstraction and Encapsulation. Benefits of Abstraction & Encapsulation. Concrete Types. Using Typedefs to streamline classes.

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Review Questions II KEY

C++ Exception Handling 1

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

The Standard Template Library. An introduction

14. Pointers, Algorithms, Iterators and Containers II

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

CSCE 110 PROGRAMMING FUNDAMENTALS

BITG 1113: Function (Part 2) LECTURE 5

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

Transcription:

Functions in C++ Functions For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Declarations vs Definitions Inline Functions Class Member functions Overloaded Functions Pointers to functions Recursive functions Piyush Kumar Function body is a scope What you should know? Defining a function // return the greatest common divisor int gcd(int v1, int v2) while (v2) int temp = v2; v2 = v1 % v2; v1 = temp; return v1; Non-reference parameter. Gcd Example 1071,1029 1029, 42 42, 21 21, 0 Another scope. temp is a local variable function gcd(a, b) if b = 0 return a else return gcd(b, a mod b) Calling a function? #include <iostream> using std::cout; using std::endl; using std::cin; // get values from standard input cout << "Enter two values: \n"; int i, j; cin >> i >> j; // call gcd on arguments i and j // and print their greatest common divisor cout << "gcd: " << gcd(i, j) << endl; Function return types Parameter Type-Checking // missing return type Test(double v1, double v2) /* */ int *foo_bar(void) /* */ void process ( void ) /* */ int manip(int v1, v2) /* */ // error gcd( hello, world ); gcd(24312); gcd(42,10,0); gcd(3.14, 6.29); // ok? // Statically typed language int manip(int v1, int v2) /* */ // ok 1

Pointer Parameters Const parameters #include <iostream> #include <vector> using std::vector; using std::endl; using std::cout; void reset(int *ip) *ip = 0; // changes the value of the object to which ip points ip = 0; // changes only the local value of ip; the argument is unchanged Fcn(const int i) Fcn can read but not write to i. int i = 42; int *p = &i; cout << "i: " << *p << '\n'; // prints i: 42 reset(p); // changes *p but not p cout << "i: " << *p << endl; // ok: prints i: 0 Reference Parameters // vec is potentially large, so copying vec might be expensive // use a const reference to avoid the copy void print(const vector<int> &vec) for (vector<int>::const_iterator it = vec.begin(); it!= vec.end(); ++it) if (it!= vec.begin()) cout << " "; cout << *it; cout << endl; Can be used to return information vector<int> vec(42); print(vec.begin(), vec.end()); // Defined on next slide print(vec); Passing Iterators // pass iterators to the first and one past the last element to print void print(vector<int>::const_iterator beg, vector<int>::const_iterator end) while (beg!= end) cout << *beg++; if (beg!= end) cout << " "; // no space after last element cout << endl; Const references Passing reference to a pointer // When you don t what the function to modify the value associated with // the reference bool isshorter(const string &s1, const string &s2) return s1.size() < s2.size(); // swap values of two pointers to int void ptrswap(int *&v1, int *&v2) int *tmp = v2; v2 = v1; v1 = tmp; // v1 and v2 are the pointers passed to ptrswap themselves, // just renamed // The following link is out of the reach of this course: // Reading C/C++ declarations: http://www.unixwiz.net/techtips/reading-cdecl.html 2

Array parameters No return values? void printvalues(const int ia[10]); Parameter treated as const int * void swap (int &v1, int &v2); Returning from main Returning a reference #include <cstdlib> bool some_failure = false; if (some_failure) return EXIT_FAILURE; else return EXIT_SUCCESS; #include <string> using std::string; #include <iostream> using std::cout; using std::endl; //inline version: find longer of two strings inline const string & shorterstring(const string &s1, const string &s2) return s1.size() < s2.size()? s1 : s2; string s1("successes"), s2("failure"); cout << shorterstring(s1, s2) << endl; Tip 1: Never return a reference to a local object. Tip 2: Never return a pointer to a local object. Put these in header files. is the process a procedure goes through when one of the steps of the procedure involves rerunning the entire same procedure. function factorial(n) if (n <= 1) return 1; else return n * factorial(n-1); Fibonacci number sequence: F(n) = F(n 1) + F(n 2). 3

template <typename T> void recsort(t begin, T end) int len = distance(begin,end); if( len <= 1) return; for(int i = 1; i < len; ++i) if(*(begin+i) < *(begin)) swap( *(begin+i), *(begin) ); recsort(begin+1,end); vector<int> vs; int N = 10; for(int i = 0; i < N; ++i) vs.push_back(rand()); recsort(vs.begin(), vs.end()); for(int i = 0; i < N; ++i) cout << vs[i] << endl; template <typename T> void recsort(t begin, T end) int len = distance(begin,end); if( len <= 1) return; for(int i = 1; i < len; ++i) if(*(begin+i) < *(begin)) swap( *(begin+i), *(begin) ); recsort(begin+1,end); Generates void recsort(vector<int>::iterator begin, vector<int>::iterator end) int len = distance(begin,end); if( len <= 1) return; for(int i = 1; i < len; ++i) if(*(begin+i) < *(begin)) swap( *(begin+i), *(begin) ); recsort(begin+1,end); Can you see the recursion in a Sudoku solver? Another example. void printnum(int n) if (n >= 10) printnum(n/10); print(n%10); Another version. void printnumb(int n, int b) if (n >= b) printnumb(n/b); print(n%b); Eight Queens problem: Brute force solution: 64^8 = 2^48 = 281,474,976,710,656 possible blind placements of eight queens, The eight queens puzzle is based on the problem of putting eight chess queens on an 8 8 chessboard such that none of them is able to capture any other using the standard chess queen's moves. Invariants: no two pieces can share the same row any solution for n queens on an n m board must contain a solution for n 1 queens on an (n 1) m board proceeding in this way will always keep the queens in order, and generate each solution only once. 4

Backtracking A strategy for guessing at a solution and backing up when an impasse is reached and Backtracking can be used together to solve our problem (and many other problems) Eight Queens An observation that eliminates many arrangements from consideration No queen can reside in a row or a column that contains another queen Now: only 40,320 (8!) arrangements of queens to be checked for attacks along diagonals Eight Queens The Eight Queens Problem A recursive algorithm that places a queen in a column Base case If there are no more columns to consider You are finished Recursive step If you successfully place a queen in the current column Consider the next column If you cannot place a queen in the current column You need to backtrack Figure 5.1 a) Five queens that cannot attack each other, but that can attack all of column 6; b) backtracking to column 5 to try another square for the queen; c) backtracking to column 4 to try another square for the queen and then considering column 5 again Default Arguments Static variables. int ff(int i = 0); screen = screeninit( string::size_type height = 24, string::size_type width = 80, char background = ); string screen = screeninit(); string screen = screeninit(66); string screen = screeninit(66,256); string screen = screeninit(66,256, # ); string screen = screeninit(,,? ); // error string screen = screeninit(? ); // calls (?,80, ); Retain their values across function calls. In this course you are barred from using them. You can also call functions to initialize default Arguments. These functions are called when the function is called. 5

Function overloading Functions having same name but different parameter types. Record lookup(const Account&); Record lookup(const Phone&); Record lookup(const Name&); Record lookup(const SS&); 6