Download presentation
Presentation is loading. Please wait.
Published byΠαρθενιά Αποστολίδης Modified over 6 years ago
1
Addis Ababa Institute of Technology Yared Semu May 2012
Functions in Detail Addis Ababa Institute of Technology Yared Semu May 2012
2
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.
3
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 { }.
4
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.
5
Program Flow With Functions
6
Todo: [Example]
7
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
8
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.
9
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.
10
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)
11
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);
12
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);
13
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);
14
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.
15
// 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;
16
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;
17
Local, Global and Static Local Variables
18
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).
19
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.
20
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;
21
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.
22
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;
23
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”
24
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;
25
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;
26
Default Arguments
27
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.
28
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;
29
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):
30
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.
31
Passing by Value/ Passing by Reference
32
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.
33
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;
34
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.
35
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;
36
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;
37
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;
38
Overloaded Functions
39
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.
40
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)
41
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?
42
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.
43
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;
44
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;
45
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;
46
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;
47
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;
48
Summary Function Definition and Declaration Function Prototypes
Function call statements Argument Passing Local, Global and Local Static Variables Default Arguments
49
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(); }
50
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?
51
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).
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.