User Defined Functions

Slides:



Advertisements
Similar presentations
Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides.
Advertisements

Chapter 7: User-Defined Functions II
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
// Functions that take no arguments #include using namespace std; void function1(); void function2( void ); int main() { function1(); function2(); return.
CPSC230 Computers & Programming I Lecture Notes 20 Function 5 Dr. Ming Zhang.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
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 Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
LECTURE 11 TYPES OF USER DEFINE FUNCTIONS ITC-414.
Object Oriented Programming Spring COMSATS Institute of Information Technology Functions OOP in C++ by Robert Lafore - Chapter#5 Kaleem Ullah
Current Assignments Homework 3 is due tonight. Iteration and basic functions. Exam 1 on Monday.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Function 2. User-Defined Functions C++ programs usually have the following form: // include statements // function prototypes // main() function // function.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
CSC1201: Programming Language 2 1 Functions. 2 Function declaration: return_type FuncName( Type arg1, Type arg2,….. Type argN) { function body } A program.
Senem Kumova Metin // CS115 // FUNCTIONS CHAPTER 5.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
CS1201: Programming Language 2 Function I By: Nouf Aljaffan Edited by : Nouf Almunyif.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Functions Modules in C++ are called functions and classes. Main reason to use functions is : – get aid in conceptual organization.
 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.
Chapter 15 - C++ As A "Better C"
C++ Lesson 1.
Functions.
Topic 6 Recursion.
Introduction to Programming
Chapter 6 CS 3370 – C++ Functions.
Introduction to C++ computers and programming
CSC1201: Programming Language 2
IS Program Design and Software Tools Introduction to C++ Programming
C Functions -Continue…-.
ㅎㅎ Fourth step for Learning C++ Programming Namespace Function
Chapter 3 - Functions Outline 3.1 Introduction
Bill Tucker Austin Community College COSC 1315
A Lecture for the c++ Course
Chapter 5 Functions.
CSC113: Computer Programming (Theory = 03, Lab = 01)
FUNCTIONS IN C++.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Repetition Structures (Loops)
Global & Local Identifiers
Chapter 5 - Functions Outline 5.1 Introduction
User-defined Functions
Compound Assignment Operators in C++
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Return_DT F_name ( list of formal parameters)
User-defined Functions
Announcements Final Exam on August 19th Saturday at 16:00.
Dr. Khizar Hayat Associate Prof. of Computer Science
Variables have attributes
Local, Global Variables, and Scope
The Function Prototype
CSC1201: Programming Language 2
Programming fundamentals 2 Chapter 1: Functions (Sub-Algorithms)
Functions Imran Rashid CTO at ManiWeber Technologies.
Dr. Khizar Hayat Associate Prof. of Computer Science
CS1201: Programming Language 2
Chapter 3 - Functions Outline 3.1 Introduction
Presentation transcript:

User Defined Functions Rehab Duwairi

Default arguments: If the driver does not send a value to an argument (when calling a function) then that function will use a default value for that argument.

#include <iostream> using namespace std; double sum (double =5, double =10, double =15); void main () { double a, b, c; cout<<"please enter a, b, c\n"; cin>>a>>b>>c; cout<<sum(a, b, c)<<endl; cout<<sum(a, b)<<endl; cout<<sum(a)<<endl; cout<<sum()<<endl; } double sum (double x, double y, double z) { return x+y+z;}

if the user provides 10 for a, 20 for b and 30 for c, then the previous program will print the following values: 60 (program sets x=10, y=20 and z=30) 45 (program sets x=10, y=20, and z=15 [default]) 35 (program sets x=10, y=10 [default], and z=15 [default]) 30 (program sets x=5 [default], y=10 [default], and z=15 [default])

Overloaded functions All functions that agree on the name of the function but do not have to agree on number of parameters and on types of parameters. Sometimes we may want to carry out the same task on different number of parameters (which might be of different data types). Instead using different names for the functions, we can use the same name via overloading technique. This should make our programs easy to read.

#include <iostream> using namespace std;   int min(int, int, int); double min(double, double, double); char min(char, char, char); bool min(bool, bool); void main () { cout<<min(4, 5, -1)<<endl; cout<<min(-4.5, 5.2, -1.1)<<endl; cout<<min('a', 'c', 'z')<<endl; cout<<min(true, false)<<endl; }

int min (int a, int b, int c) { int z = a; if(b < z) z = b; if(c < z) z = c; return z; } double min (double a, double b, double c) { double z = a;

char min (char a, char b, char c) { char z = a; if(b < z) z = b; if(c < z) z = c; return z; } bool min (bool a, bool b) { if (a < b ) return a; else return b; } From the type and number of arguments, the compiler will figure out the version of the function to call.

inline functions: The overhead associated with function calls may exceed the benefit of having functions. This is typically true for small functions that calculate expressions. C++ allows programmers to write the keyword inline before the function return type so that the compiler will assess the cost of calling that function. If the cost is little then the compiler will call that function; otherwise the compiler will replace the function call by its definition. Reason for this is that compilers want to execute code fast (efficiency).

#include <iostream> using namespace std; inline int sum (int a, int b, int c) { return a+b+c;} void main () { int x, y, z; cin>>x>>y>>z; cout<<sum(x, y, z)<<endl; }   From a user point of view, the behavior of the above program will be similar to the case where inline is not used.

Recursive functions A recursive function is a function that calls itself. Recursion has a base case and a general case. In the base case the function return a constant, in the general case, the function calls itself one or more times. Recursion relies on if statements.

A recursive function that calculates xy. Note that xy= x A recursive function that calculates xy. Note that xy= x * xy-1 and x0=1 and x1=x int power (int x, int y) { if ((y == 1) return x; else if (y == 0) return 1; else return x * power(x, y-1); }

What can be achieved by recursion can be achieved by iteration. xy= x * x * … * x (y times).   The same power function with iteration: int power (int x, int y) { int s=1; for (int i=1; i<=y; i++) s=s*x; return s; }

Fibonacci numbers are defined as Fib(0)=1, fib(1) = 1, fib(2)=2, fib(3)=3, fib(4) = 5, fib(5) = 8. In general fib(n) = fib(n-1) + fib(n-2). //A recursive fib function int fib(int n) { if ((n == 1) || (n == 0)) return 1; else return fib(n-1) + fib (n-2); } Iterative fib (was solved in a previous lecture) Recursive functions are easier to code than iterative functions.

What is the output of the following program What is the output of the following program? #include <iostream> using namespace std; void my_function (int &, int); void main() { int a =5; int b=10; my_function(a, b); cout<<" a ="<< a <<endl; cout<<" b = "<< b <<endl; } void my_function(int & m, int n) { m++; n--; a =6 b = 10 Press any key to continue

What is the output of the following program What is the output of the following program? #include <iostream> using namespace std; int sum (int a, int b) {return a+b;} bool sum(bool a, bool b) {return a || b;} void main () { cout<<sum(2, 3)<<endl; cout<<sum(true, false)<<endl; } 5 1 Press any key to continue

#include <iostream> using namespace std; int sum (int n) { if (n == 1) return 1; else return n + sum(n-1); } void main () { cout<< sum(4) << endl; Answer is 10.

What will be printed by the following program What will be printed by the following program? #include <iostream> using namespace std; void fun1(int &, int &, int); void main () { int a = 10, b=20, c=30; fun1(a, b, c); cout<<"a = "<<a<<endl; cout<<"b = "<<b<<endl; cout<<"c = "<<c<<endl; } void fun1(int &a, int &b, int c) { a = 50; b=60; c=70;} 50 60 30

// tower of Hanoi recursively #include <iostream> using namespace std; void solveHanoi (int n, char pegFrom='x', char temp='y', char pegTo='z’); int main() { int number; cout<<"type number of disks \n"; cin>>number; solveHanoi(number); return 0; } void solveHanoi(int n , char from , char temp, char to) if (n==1) cout << from << " > " << to << endl; else solveHanoi (n-1, from, to, temp); solveHanoi (n-1, temp, from, to); } //end function

1) Storage classes of varaibles scope has to do with "where the variable is seen" storage class has to with "how long the variable exists": auto static

#include <iostream> using namespace std; void fun(); void main () { fun(); } void fun() { static int b=1; b++; cout<<b<<endl; The output is 2 3 4

Variable scopes (contexts) Variables in C++ have 4 scopes: a) File scope: these are variables defined outside any function. They are known (and therefore can be accessed) in any function that follows their definitions. These global variables (which have file scope) are suitable for global values such as PI or e. b) Block scope: these are defined inside blocks inside functions. They are known to the block in which they are defined. c) Function scope: these are variables that are defined inside functions such as main or user defined function. They are known and accessed inside the function from the point they are defined and onwards. d) Function prototype scope: these are defined inside function prototypes and are seen only by the function prototype.

#include <iostream.h> int a = 5; //global or file scope Example 1: //variable scopes #include <iostream.h> int a = 5; //global or file scope void fun(int a); //function prototype scope void main () { int a = 10; //local variable to main. function scope cout<< "main a "<<a<<endl; { int a=15; //local variable to block: block scope cout<<"block a "<<a<<endl; cout<<"global a"<<::a<<endl; } cout<<"main a " << a<<endl; cout<<"global a "<< ::a<<endl; fun(a); //function call } //end main //function definition void fun (int a) { //function scope cout<<"function a "<<a<<endl; a = 20; cout<<::a<<endl;

The output: 10 15 5 10

The following diagram shows the nesting that we have in the above example:

Example 2: #include <iostream> Using namespace std; int x=5; //x has a file scope void fun(int a, int b); // a and b have function prototype scope void main() { int a=10; //a has function scope. Local to main int c = a+x; //c has function scope local to main // can see and use global variable x. cout<<"c = "<<c<<endl;// c will be 15 { int m =x+a; //m has block scope; block can see both global x and //variable a cout<<"m = "<<m<<endl; // m will be 15 } fun(a,x); //function call void fun(int a, int b){//a and b have function scope cout<<a+b+x<<endl; //values of local variables a and b are set by function //call in main () // also function fun() can see and use global variable x // value printed will be 20.

Static variables: Users can define static variables. Static variables live throughout program execution and are initialized to zero by the system.   Example 1: //static variables #include <iostream> using namespace std; void temp() { static int y; //initialization is done by system cout<<y<<endl; } void main () { temp(); } The output of the previous program is 0

#include <iostream> using namespace std; void temp() { static int y=1; y = y + 5; cout<<y<<endl; } void main () { temp(); }   The output of the previous program is 6 11 16 The idea is that static variables live (or exist) throughout program execution and retain (keep or save) their values between function calls.

addone1(a); //call addone1 1) call value and call reference void addone1(int a) { a++; } void addone2 (int &a) {a++;} void main () { int a=5; cout<<"the value of a before calling any function \n"<< a <<end; addone1(a); //call addone1 cout<<"the value of a after calling addone1 \n"<<a << endl; addone2(a); // call addone2 cout<<"the value of a after calling addone2 \n" <<a << endl; }

#include <iostream> using namespace std; void main () { int count = 1; int &R = count; int X = count; R++; //count++; cout<<"count = "<<count <<endl; }

#include <iostream> using namespace std; design a function that will return more than one value. input: length and width of a rectangle output: area, circumference #include <iostream> using namespace std; void area_cir(int x, int y, int &area, int &cir) { area= x*y; cir = 2*(x+y); } void main () { int a, b; cout<<"type in length \"; cin>>a; cout<<"type in width \n"; cin>>b; int area, cir; area_cir(a, b, area, cir); cout<< "Area = "<< area <<endl; cout<<"Circumference = "<<cir <<endl;