Addis Ababa Institute of Technology Yared Semu May 2012

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
Chapter 5 Functions.
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.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
// 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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
 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.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Chapter 6: Functions.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
CS102 Introduction to Computer Programming Chapter 6 Functions Continued.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Programming Languages -2 C++ Lecture 3 Method Passing Function Recursion Function Overloading Global and Local variables.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals Enumerations and Functions.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
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
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Chapter 7: User-Defined Functions II
Chapter 5 Functions.
FUNCTIONS IN C++.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
Introduction to Functions
Chapter 4 void Functions
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.
Functions.
6 Chapter Functions.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Programming fundamentals 2 Chapter 1: Functions (Sub-Algorithms)
Functions Imran Rashid CTO at ManiWeber Technologies.
Instructor: Hidayah Elias Course: COMPUTER PROGRAMMING (BFC 2042)
Standard Version of Starting Out with C++, 4th Edition
Functions Chapter No. 5.
Presentation transcript:

Addis Ababa Institute of Technology Yared Semu May 2012 Functions in Detail Addis Ababa Institute of Technology Yared Semu May 2012

Recap… What is a Function? A function is a collection of statements that perform a specific task. Why do we need Functions? Functions break a program into small, manageable units. This is called Modular Programming.

Function Definition and Declaration type name ( parameter1, parameter2, ...) { statements } Where: TYPE : is the data type that specifies of the data or value returned by the function. NAME : is the identifier by which it will be possible to call the function. Naming rules are the same as those for variables PARAMETER LIST : (as many as needed): a list of variables that hold values being passed into the function. The different parameters are separated by commas. STATEMENT(S) : is the function's body. It is a block of statements surrounded by braces { }.

Calling a Functions A function is executed when it is called. Function main is called automatically when a program starts, but all other functions must be executed by function call statements. A function call is simply the name of the function followed by a set of arguments enclosed in parentheses and a semicolon.

Program Flow With Functions

Todo: [Example]

So far, we have been defining our functions before using them So far, we have been defining our functions before using them. The definition of a function used to come before the main function or any other function that used it. However, these are the only things a compiler needs to know before it encounters a call to a function The name of the function The number and type of parameters for the function The return type of the function

Function Prototypes How do you ensure that the compiler knows about the function before a function is called the first time. Well, You’ve two Options: Currently Employed Method: Define the function before its call. Use Function Prototypes.

Function Prototypes_02 A function prototype (also known as a function declaration) provides all the information a compiler needs before encountering a function call. Function prototypes are usually placed near the top of a program so the compiler will encounter them before any function calls. A function prototype looks similar to the function header, except there is a semicolon at the end.

Creating and calling a user defined function: At the beginning of your program declare the function (Function Prototype) Some where in your program, define the function (Function Definition) Other functions can then call the function (Function Call Statement)

Function Prototypes A function Prototype eliminates the need to place a function definition before all calls to the function. Syntax: ReturnType FunctionName (ParameterList); Example: double add( double x, double y);

Function Definition The function definition statements (i.e. body of the function) states what the function actually does. Syntax: return_type function_name (parameter_list) { //Function body statements } Example: double add (double a, double b) return (a+b);

Function Call Statement A function call statement is a statement that causes a function to execute. Syntax: Demo : Four- Function Calculator function_name (argument_list); Example: double result =add(3,2);

Argument Passing: Sending Data into a function Arguments: are Values that are sent into a function Parameters: are special variables that hold the value being passed as an argument into a function.

// This program demonstrates a function with a parameter. #include <iostream> using namespace std; void displayValue(int); int main() { cout << "I am passing 5 to displayValue.\n"; displayValue(5); // Call displayValue with argument 5 cout << "Now I am back in main.\n"; return 0; } void displayValue(int num) cout << "The value is " << num << endl;  

void swap(int x, int y); //void swap(int, int); //this is also possible int main() { int first = 10, second = 20; cout<<”Before Swap: First = “ <<first<<” Second = “<<second; swap(first, second); cout<<”\nAfter Swap: First = return 0; } void swap(int x, int y) int temp = x; x = y; y = temp; cout<<”\nIn swap: x = “<<x<<” y = “<<y;

Local, Global and Static Local Variables

Local and Global Variables A Local Variable is defined inside a function and is not accessible outside the function. A Global Variable is defined outside all functions and is accessible to all functions in its scope (those that come after its definition).

Local and Global Variables If a function has a local variable with the same name as a global variable, the local variable is preferred in the function. Note: You can use the scope resolution (::) operator to access the global variable. Global Variables are initialized to “zero” by Default.

Practice Makes Perfect! void anotherFunction() { int num = 20; cout<<“ In another Function Number is”<<num; } int main() int num = 1; //Local to main cout<<“In main num is”<<num<<endl; anotherFunction(); cout<<“Back in main num is still”<<num;

Practice Makes Perfect _2! #include <iostream> using namespace std; int myNum; //a global variable int main() { int a, b, myNum = 15; //local variables to main cout<<myNum<<endl; //the local variable preferred cout<<::myNum<<endl; //the global variable return 0; } For the last question, fn1 will be chosen Also, some compilers may choose to upgrade the arguments and pick fn1 for all cases.

Static Local Variables Question: Predict the output. void showLocal(); int main() { showLocal(); return 0; } void showLocal() int localNum = 5; cout<<“Local Number is”<<localNum<<endl; localNum= 10;

Static Local Variables If a function is called more than once in a program, the values stored in the function’s local variable do not persist between calls. The local functions are destroyed when the function terminates (returns to the calling function) and are recreated when the function starts again. If a local variable is made static, it will not be destroyed when the function ends and recreated when it starts again. Note the keyword “static”

Static Local Variables Question: Predict the output. void showLocal(); int main() { showLocal(); return 0; } void showLocal() static int localNum = 5; cout<<“Local Number is”<<localNum<<endl; localNum= 10;

Example: Predict the Output void showStatic() { static int statNum; cout<<“Static Number is”<<statNum<<endl; statNum++; } int main() for (int count=0; count < 5; count++) showStatic(); return 0;

Default Arguments

Default Arguments Default Arguments are passed to parameters automatically if no argument is provided in the function call. Default Arguments are literal values or constants with an = operator in front of them appearing after the data types listed in a function prototype. Default arguments allows us to leave out an argument in a function call statement.

Example - 01 void showArea(double length = 20.0, double width = 10.0); //void showArea(double= 20.0, double =10.0); int main() { showArea(); showArea(12.0); showArea(12.0, 5.5); return 0; } void showArea(double length, double width) double area = length * width; cout<<“The area is”<<area<<endl;

Example(2): //Function prototype with default arguments void displayStars(int=10,int=1); //void displayStars(int cols = 10, int rows = 1) //This is also possible int main() { displayStars(); cout<<endl; displayStars(5); displayStars(7,3); return 0; } void displayStars(int cols, int rows) for (int down = 0; down < rows; down++) for (int across = 0; across < cols ; across++) cout<<“*”; Example(2):

KIMs (Keep in Mind) The value of a default arguments must be literal value or a named constant. When an argument is left out of a function call (because it has a default value), all the arguments that come after it must be left out. Example When a function has a mixture of parameters both with and without default arguments, the parameters with default arguments must be defined last.

Passing by Value/ Passing by Reference

Passing by Value When an argument is passed into a parameter by value, only a copy of the argument’s value is passed. Changes to the parameter don’t affect the original argument. If a parameter value is changed inside a function, it has no effect on the original argument.

Example: Passing by Value void swap(double a, double b) { double temp; temp = a; a= b; b = temp; } int main() double x = 2; double y= 3; cout<<“Value of X:”<<x<<endl; cout<<“Value of Y:”<<y<<endl; swap(x,y); return 0;

Passing by Reference A reference variable is an alias for another variable. When used as a parameter, a reference variable allows a function to access the parameter’s original argument. Any change to the parameter is actually made to the original argument. Reference variable are defined like regular variables, except there is an ampersand (&) in front of the name.

void swap(double &, double &); int main() { double x = 2; double y= 3; cout<<“Value of X:”<<x<<endl; cout<<“Value of Y:”<<y<<endl; swap(x,y); return 0; } void swap(double &a, double &b) double temp; temp = a; a= b; b = temp;

void doubleNum(int &); int main() { int value = 4; cout<<“In main Value is”<<value<<endl; cout<<“Now calling doubleNum….”<<endl; doubleNum(value); cout<<“Now back in main, value is”<<value<<endl; return 0; } void doubleNum(int &refVar) refVar *= 2;

Example: Passing by Reference void swap(double &, double &); int main() { double x = 2; double y= 3; cout<<“Value of X:”<<x<<endl; cout<<“Value of Y:”<<y<<endl; swap(x,y); return 0; } void swap(double &a, double &b) double temp; temp = a; a= b; b = temp;

Overloaded Functions

Overloaded Functions So far, we have said that all function names must be unique. Two or more functions may have the same name, as long as their parameter list are different. The type of the parameters are different and/or The number of parameters are different The compiler will use the parameter list to distinguish between the overloaded functions.

Example: (2) //Function Prototypes int square(int); double square(double); int main() { int userInt; int userReal; cout<<“Enter an integer and a floating point value:”; cin>>userInt>>userReal; cout<<“Here are their squares:”; cout<<square(userInt)<<“ and ”<<square(userReal)<<endl; return 0; } int square(int number) return (number*number); double square(double number) Example: (2)

Example: (2) //the following two are ok double calcArea(double w, double h); double calcArea(double radius); //adding the following will cause trouble //double calcArea(double base, double height); //but the following is ok int calcArea(int w, int h); //fn3 //the return type has no effect on overloading //the function calls double a=1.0, b=4.0; int c=4, d=5; calcArea(a, b); calcArea(a); calcArea(c, d); calcArea(a, c); //guess who will be chosen?

Q1. Function Definition Basics: Write a function that takes four integer arguments and returns the minimum of the four arguments. Raising a number n to a power p is the same as multiplying n by itself p times. Write a function called power() that takes a double value for n and an int value for p, and returns the result as a double value. Use a default argument of 2 for p, so that if this argument is omitted, the number n will be squared.

Q2. Scope of Variables – Nested and Parallel Scopes (What is the ouput void function1(); //function1 is global void function2(); //function2 is global int x = 11; //this x is global int main() { int x = 22; int x= 33; cout<<“In block inside main(): x = ”<< x <<endl; } cout<<“In main() : x = ”<<x<<endl; cout<<“In main(): ::x =”<<::x<<endl; function1(); function2(); void function1() { int x = 44; cout<<“In f1(): x=”<<x<<endl; } void function2() cout<<“In f2():x=”<<x<<endl;

Q3. Static Local Variables (What is the output?) #include <iostream> using namespace std; void showStatic() { static int a=0; cout<<a<<endl; a++; } int main() for (int i=0; i<10; ++i) showStatic(); return 0;

Q4. Passing by Value/Reference void getNums(int&,int&); void orderNums(int&,int&); int main() { int small, big; getNums(small,big); orderNums(small,big); return 0; } void getNums(int &a,int&b) { cout<<“Enter an integer:”; cin>>a; //User Enters: 15 cout<<“Enter a second integer:”; cin>>b; //User Enters:10 } void orderNums(int &a, int &b) int temp; if(a > b) temp = a; a = b; b = temp;

Q4. Default Arguments void repchar(char=‘*’, int = 10); //Declaration with default arguments (Prototype) int main() { repchar(); repchar(‘+’,8); repchar(‘=’); return 0; } //Function Definition void repchar(char ch ,int n) for (int j = 0; j < n ; j++) cout<<ch; cout<<endl;

Q5. Overloaded Functions int divide(int a, int b) { return (a/b); } float divide(double a, double b) int main() int x = 5, y = 2; double n = 5.0, m = 2.0; cout<<divide(x,y); cout<<“\n”; cout<<divide(n,m); return 0;

Summary Function Definition and Declaration Function Prototypes Function call statements Argument Passing Local, Global and Local Static Variables Default Arguments

Recursion So far we have seen functions that call other functions. It is also possible for a function to call itself. A function that calls itself is known as a recursive function. void sayHello() { cout<<”Hello Recursively\n”; sayHello(); }

Reading Assignment When will a recursive function stop calling itself? How are recursive function calls handled? How do returns from recursive functions behave? Why are recursive functions necessary?

Mid Exam: Question Types Exam Date: May 18, 2012 1. Some theoretical concepts. 2. Given a program segment, predict the output that you would expect when the program is run. 3. Identify and fix errors found in a give program segment. 4. Write a full-blown error-free program(s).