Functions Prototypes, parameter passing, return values, activation frams.

Slides:



Advertisements
Similar presentations
Complete Structure class Date {class Date { private :private : // private data and functions// private data and functions public :public : // public data.
Advertisements

Recursion.
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
1 Pointers and Strings Section 5.4, , Lecture 12.
User Defined Functions
For(int i = 1; i
Computer Science 1620 Math Library. Remember this program? suppose that I invest $25000 into a mutual fund that returns 8% per year. Write a program to.
Part 1 Landscape Hannu Laine. Pointer parameters //prototype of swap void swap(int *a, int *b); //application void main(void) { in number1 = 1, number2.
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
Computer Science 1620 Function Overloading. Review Question: suppose I have the following function: can I call this function with an integer? yes – compiler.
1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline some useful problems.
Template Implicit function overload. Function overload Function overload double ssqq(double & a, double & b) { return(a*b);} float ssqq(float & a, float.
Review What is a virtual function? What can be achieved with virtual functions? How to define a pure virtual function? What is an abstract class? Can a.
Review of Inheritance. 2 Several Levels of Inheritance Base Class B Derived class D Derived class D1.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
第三次小考. #include using namespace std; int aaa(int *ib,int a1,int a2) { int u,v; int m=(a1+a2)/2; if(a1==a2)return ib[a1]; u=aaa(ib,a1,m); cout
PASSING PARAMETERS 1. 2 Parameter Passing (by Value) Parameters Formal Parameters – parameters listed in the header of the function Variables used within.
AU/MITM/1.6 By Mohammed A. Saleh 1. Arguments passed by reference  Until now, in all the functions we have seen, the arguments passed to the functions.
CS Feb 2007 Chap 6. Functions General form; type Name ( parameters ) { … return value ; }
Function Overloading Can enables several functions Of same name Of different sets of parameters (at least as far as their types are concerned) Used to.
1 6/20/2015CS150 Introduction to Computer Science 1 Functions Chapter 6, 8.
CS Oct 2006 Chap 6. Functions General form; type Name ( parameters ) { … return value ; }
Functions Pass by Value Pass by Reference IC 210.
Function 2 (L17) * Function Prototype * Promotion Rules * Data Type * Library Header File * Customer Header File * Case Study * Exercise/Home Work Dr.
Searching Arrays Linear search Binary search small arrays
1 Arrays & functions Each element of an array acts just like an ordinary variable: Like any ordinary variable, you can pass a single array element to a.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
FUNCTIONS (a) Value returning e.g. int main() ….…. return 0; (b) Void (returning) no return statements example To print this message **** ** Welcome.
FUNCTIONS IN C++. DEFINITION OF A FUNCTION A function is a group of statements that together perform a task. Every C++ program has at least one function,
Instructor - C. BoyleFall Semester
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
/* example program to demonstrate the passing of an array */ #include int maximum( int [] ); /* ANSI function prototype */ int maximum(
The This Pointer Programming in C++ Fall 2008 Dr. David A. Gaitros
Function prototype A function must be declared before it can be referenced. One way to declare a function is to insert a function prototype before the.
Function 2. User-Defined Functions C++ programs usually have the following form: // include statements // function prototypes // main() function // function.
CSCI 161 Lecture 14 Martin van Bommel. New Structure Recall “average.cpp” program –Read in a list of numbers –Count them and sum them up –Calculate the.
Print Row Function void PrintRow(float x[ ][4],int i) { int j; for(j=0;j
 Memory setup  Pointer declaration  Address operator  Indirection  Printing addresses or pointers.
Lesson xx Why use functions Program that needs a function Function header Function body Program rewritten using a function.
Computer Programming II Lecture 4. Functions - In C++ we use modules to divide the program into smaller and manageable code. These modules are called.
Announcements. Practice questions, with and without solutions will be uploaded by Friday 5 th November, make sure to check them before the weekend \\netstorage\Subjects\ITCA-b\Exam.
Searching Arrays Linear search Binary search small arrays
Introduction to Programming Using C
Array An “average.cpp” program
CSC 253 Lecture 8.
CSC 253 Lecture 8.
Chapter 5 Function Basics
Value returning Functions
Pointers & Functions.
Anatomy of a Function Part 1
الوحدة الرابعة البرمجة وصياغة حل المسائل البرمجة وأهميتها أهداف الدرس الأول مفهوم البرمجة. الفرق بين المبرمج ومستخدم البرنامج. الحاجة إلى البرامج.
CS150 Introduction to Computer Science 1
Lec 14 Oct 23, 02.
CS149D Elements of Computer Science
Function Overloading.
Function Defaults C++ permits functions to be declared with default values for some, or all, of its parameters Allows for the function to be called without.
CS150 Introduction to Computer Science 1
Fundamental Programming
List Iterator Implementation
Pointers & Functions.
The Stack.
Anatomy of a Function Part 1
Unit-1 Introduction to Java
Introduction to Algorithms and Programming COMP151
Presentation transcript:

Functions Prototypes, parameter passing, return values, activation frams

Why Functions? Suppose you want to print the maximum of two numbers... int i1 = 5, i2 = 23; if (i1 > i2) cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << i1 << endl; else cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << i2 << endl;...

Why Functions? Now suppose you want to print the maximum of two numbers many times int i1 = 5, i2 = 23; if (i1 > i2) cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << i1 << endl; else cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << i2 << endl; i1 = 17; i2 = 13; if (i1 > i2) cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << i1 << endl; else cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << i2 << endl; i1 = 33; i2 = 33; if (i1 > i2) cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << i1 << endl; else cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << i2 << endl;

A Better Approach int max(int i, int j){ int maxNumber; if (i > j) maxNumber = i; else maxNumber = j; return maxNumber; } int i1 = 5, i2 = 23; cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << max(i1, i2) << endl; i1 = 17; i2 = 13; cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << max(i1, i2) << endl; i1 = 33; i2 = 33; cout << “The max of ” << i1 << “ and ” << i2 << “ is ” << max(i1, i2) << endl;

Why Functions? Functions Isolate code for specific task Make code easier to read and to understand Confine error search to function definition if bugs Support and encourage reuse

Example Function /* prime_test.cpp * Author: Richard Newman * Date: 5/25/14 * Test input numbers for primality */ #include using namespace std; bool isPrime(int candidate){// naive prime test // note i <= needed else 4 returns true for (int i = 2; i <= candidate/2; ++i) { if (candidate % i == 0) return false; } return true; }

int main() { int i = 2; cout << "Test for primality" << endl; cout << "Enter 1 to quit" << endl; while (i > 1) { cout << "Number to test: " << flush; cin >> i; if (i != 1) cout << i; if (i < 1) cout << " is not valid" << endl; else if (i > 1) { if (isPrime(i)) cout << " is prime" << endl; else cout << " is not prime" << endl; } cout << "Bye" << endl; Return 0; }

What is happening? The function has two parts: Function header Function body (or definition) bool isPrime(int candidate) {// naive prime test // note i <= needed else 4 returns true for (int i = 2; i <= candidate/2; ++i) { if (candidate % i == 0) return false; } return true; }

What is happening? The function header has several parts: Return value type – bool Function name – isPrime Formal parameter(s) – int candidate Function signature = Name + formal parameter list bool isPrime(int candidate)

Function Prototypes: Forward Declaration To find the right function to call the compiler has to build into the symbol table not just the function name, but its signature and type. This allows the right call to be made, the right amount of space to be pushed onto the stack, and the types to be checked at compile time bool isPrime(int candidate);

Example Prototype /* prime_test.cpp * Author: Richard Newman * Date: 5/25/14 * Test input numbers for primality */ #include using namespace std; bool isPrime(int candidate);... Main() {... }... bool isPrime(int candidate){... }

Command Line Args Often want to pass command line arguments into program to allow for user to specify inputs, modes, etc. without user interaction while the program is running Great for use in scripts! $ prime_test2 -h -s

Modify to take cmdline args... const string HELP = "prime_test2 [-s] [-h] \n" "\tCommand line parameters:\n" "\t\t-s: silent mode - no prompts, 0/1 output\n" "\t\t-h: print this help info first\n" "\tInput:\n" "\t\t1 to quit\n" "\t\tnumbers greater than 1 to output primality\n" "\t\tnumbers <1 are invalid\n" "\tOutput:\n" "\t\tOn valid input, states if input is prime or not\n" "\t\tIn silent mode, output is 1 if prime, 0 if not\n"; const string SOPT = "-s"; const string HOPT = "-h";

int main(int argc, char *argv[]) { bool silent = false;// silent mode const bool debug = true; // print info to debug if (debug) { cout << argc << endl; for (int i = 0; i < argc; ++i) { cout << argv[i] << endl; } for (int n = 1; n < argc; n++) { // parse cmdline if (argv[n] == SOPT) silent = true; else if (argv[n] == HOPT) cout << HELP << endl; else cerr << "Invalid commandline argument: " << argv[n] << endl; } int i = 2; if (!silent) { cout << "Test for primality" << endl; cout << "Enter 1 to quit" << endl; }

while (i > 1) { if (!silent) { cout << "Number to test: " << flush; } cin >> i; if (!silent & (i != 1)) { cout << i; } if (i < 1) { if (!silent) { cout << " is not valid" << endl; } else if (i > 1) { if (isPrime(i)) { // prime if (!silent) { cout << " is prime" << endl; } else { cout << "1" << endl; } else { // not prime...

if (!silent) { cout << " is not prime" << endl; } else { cout << "0" << endl; } if (!silent) { cout << "Bye" << endl; } return 0; }