Functions - Portal UniMAP
Download
Report
Transcript Functions - Portal UniMAP
Week 6 – Functions (2)
UniMAP SemI-11/12
EKT150
1
Outline
Recall - sample application
functions that do not return value
functions that return a value
Recall – global variable vs. local variable
Passing parameters in functions :- Pass by value
Functions that return more than one value
Sample application-functions that return more than one value
Passing parameters in functions :- Pass by reference
Sample application
Recursive function
UniMAP SemI-11/12
EKT150
2
Sample application
Write a C program that reads item code and quantity,
then calculates the payment. Use functions:
fnMenu – print item code menu
fnDeterminePrice – determine price based on
item code
fnCalc - calculate payment
fnPrintResult – print payment
What argument
names do I want
to feed in as
parameters and
what to return??
Think!! Which
function returns no
value and which
function returns a
value.
EKT150
3
Sample application
#include <stdio.h>
void fnMenu();
float fnDeterminePrice(int);
float fnCalc(float,int);
void fnPrintResult(float);
int main()
{ int iCode,iQty;
float fPrice,fPay;
fnMenu();
printf("Enter item code and quantity: ");
scanf("%d %d", &iCode,&iQty);
fPrice = fnDeterminePrice(iCode);
fPay = fnCalc(fPrice,iQty);
fnPrintResult(fPay);
return 0;
}
EKT150
4
void fnMenu()
{
printf("Code\tItem\tPrice\n");
printf("1\tPapaya\t1.00\n");
printf("2\tMelon\t2.00\n");
printf("3\tDurian\t3.00\n");
printf("\tOthers\t4.00\n");
}
float fnDeterminePrice(int iItemCode)
{ float fPricing;
switch(iItemCode)
{
case 1:fPricing = 1.00;break;
case 2:fPricing = 2.00;break;
case 3:fPricing = 3.00;break;
default:fPricing = 4.00;
}
return(fPricing);
}
float fCalc(float fItemPrice, int iQuality)
{ float fTotal;
fTotal = fItemPrice*iQuantity;
return(fTotal);
}
void fnPrintResult(float fPayment)
{ printf("Payment is %.2f\n", fPayment);
}
Code
1
2
3
Item
Price
Papaya 1.00
Melon
2.00
Durian
3.00
Others
4.00
Enter item code and quantity: 1 3
Payment is 3.00
***************************
Code Item
Price
1
Papaya 1.00
2
Melon
2.00
3
Durian
3.00
Others
4.00
Enter item code and quantity: 9 3
Payment is 12.00
5
Global Variable vs. Local Variable
#include <stdio.h>
modification
void fnMenu();
float fnDeterminePrice(int);
float fnCalc(float,int);
void fnPrintResult(float);
int iCode,iQty; float fPrice,fPay;
int main()
{
fnmenu();
printf("Enter item code and
quantity:");
scanf("%d %d", &iCode,&iQty);
fPrice= fnDeterminePrice(iCode);
fPay=fnCalc(fPrice,iQty);
fnPrintResult(fPay);
return 0;
}
void fnMenu( )
{
printf("Code\tItem\tPrice\n");
printf("1\tPapaya\t1.00\n");
printf("2\tMelon\t2.00\n");
printf("3\tDurian\t3.00\n");
printf("\tOthers\t4.00\n");
}
float fnDeterminePrice(int iCode)
Output:
{
Code Item
Price
iCode--;
1
Papaya 1.00
switch(iCode)
2
Melon
2.00
{
3
Durian
3.00
case 1:fPrice=1.00;break;
Others
4.00
case 2:fPrice=2.00;break;
Enter item code and quantity: 1 4
case 3:fPrice=3.00;break;
Payment is 16.00
default:fPrice=4.00;
}
Output:
return(fPrice);
Code Item
Price
}
1
Papaya 1.00
float fnCalc(float fPrice,int iQuantity) 2
Melon
2.00
{
3
Durian
3.00
fPay=fPay+1;
Others
4.00
fPay=fPrice*iQuantity;
Enter item code and quantity: 3 1
return(fPay);
Payment is 2.00
}
void fnPrintResult(float fPay)
{ printf("Payment is %.2f\n", fPay);
}
However, sometimes we need to do some modifications
from inside a function; using global variable will make
things worse!!!
6
Pass by Value
If a parameter is passed by value, then the
value of the original data is copied into the
function’s parameter (scope: local variable(s))
In other words, it (i.e. local variable) has its
own copy of the data
changes to copy do not change original
data
During program execution, it (i.e. local
variable) will manipulate the data stored in its
own memory space
UniMAP SemI-11/12
EKT150
7
Pass by Value (Example)
#include <stdio.h>
void fnFun1(int,int);
//function prototype
int main(void)
{
int iA=5, iB=10;
printf("Before fun 1\n“);
printf(" iA = %d iB = %d\n”, iA,iB);
fnFun1(iA, iB); //function call
printf("\nAfter fun 1\n“);
printf(" iA = %d iB = %d\n”, iA,iB);
return 0;
}
void fnFun1(int iAA,int iBB) //function definition
{
iAA++;
iBB--;
printf("\n\nInside fun 1\n)";
printf(“iAA = %d iBB = %d\n”, iAA,iBB);
}
UniMAP SemI-11/12
EKT150
Output
Before fnFun 1
iA = 5 iB = 10
Inside fnFun 1
iAA = 6 iBB = 9
After fnFun 1
iA = 5 iB = 10
8
Functions that return more
than one value
When we talk about functions that
return more than one value it also
means that we want to pass arguments
by reference
passes addresses (references), NOT value
or data
allows direct manipulation
changes will affect original data
UniMAP SemI-11/12
EKT150
9
Functions that return more
than one value
There are cases where you need to
manipulate the value of an external
variable from inside a function, thus we
pass the value by reference
UniMAP SemI-11/12
EKT150
10
Sample application
Write a C program that calculates and
prints average of 2 test marks.
Your program should have functions:
fnReadMarks – read 2 test marks
fnCalcAvg – calculate average of two test
marks
fnPrint - print average
UniMAP SemI-11/12
EKT150
11
Sample application
#include <stdio.h>
void fnReadMarks(float*,float*);
float fnCalcAvg(float,float);
void fnPrint(float);
int main(void)
{
float fMarks1, fMarks2, fAvg;
}
fnReadMarks(&fMarks1,&fMarks2);
fAvg = fnCalcAvg(fMarks1,fMarks2);
fnPrint(fAvg);
return 0;
Function that returns
more than one value arguments are passed by
reference
void fnReadMarks(float *fM1,float *fM2)
{
printf("Enter marks for test1 and test2 : ");
scanf("%f %f", fM1,fM2); //notice no &
}
float fnCalcAvg(float fM1, float fM2)
{
return((fM1 + fM2)/2);
}
void fnPrint(float fAverage)
{
printf("\nAverage marks are :%.2f\n",fAverage);
}
Output
Enter marks for test1 and test2 : 70 80
Average marks are : 75.00
12
Pass by Reference
A function’s parameter that receives the location (memory address) of
the corresponding actual variables
When we attach * (star) after the arg_type in the parameter list of a
function, then the variable following that arg_type is passed by
reference
It stores the address of the actual variable, NOT the value
During program execution to manipulate the data, the address stored
will direct control to the memory space of the actual variable
Syntax:
In function protoype and function definition, put the * (star) after the data
type
Example : void fnReadMarks(float *,float *);
In function call, put the &(ampersand) before the argument name to be
passed by reference
Example : fnReadMarks(&fMarks1,&fMarks2);
UniMAP SemI-11/12
EKT150
13
Pass by Reference
Pass by reference is useful in two situations:
when you want to return more than one
value from a function
when the value of the actual parameter
needs to be changed
UniMAP SemI-11/12
EKT150
14
Sample application
Write a C program that reads character and
calculates numbers of vowel and consonant
Your program should have function:
fnRead – read character
fnFindCountVC – determine and calculate
number of vowel or consonant
fnPrint - print number of vowel or consonant
UniMAP SemI-11/12
EKT150
15
Sample application
#include <stdio.h>
#include <string.h>
char fnRead();
void fnFindCountVC(char, int*, int*);
void fnPrint(int,int);
Enter character : f
Do you want to continue?y
Enter character : I
Do you want to continue?y
Enter character : k
Do you want to continue?n
Number of vowel : 1
Number of consonant : 2
void fnFindCountVC(char cCh1, int *iVowel, int
int main()
*iConsonant)
{ char cCh, cChoice; int iCountV=0, iCountC=0;
{
do
switch(cCh1)
Functions that “return”
{ cCh = fnRead();
{
case 'A':
more than one value i.e.
fnFindCountVC(cCh, &iCountV, &iCountC);
case 'a':
arguments are passed by
printf("Do you want to continue? ");
case 'E':
reference
scanf("%c", &cChoice);
case 'e':
getchar();
case 'I':
}while((cChoice == 'y') ||(cChoice =='Y'));
case 'i':
print(iCountV,iCountC);
case 'O':
return 0;
case 'o':
}
case 'U':
case 'u': *iVowel = *iVowel +1;break;
char fnRead()
default: *iConsonant = *iConsonant + 1;
{
char cCh1;
}
printf("Enter character : ");
}
scanf("%c", &cCh1);
void fnPrint(int iVowel, int iConsonant)
getchar();
{
return(cCh1);
printf("Number of vowel : %d\n", iVowel);
}
printf("Number of consonant : %d\n", iConsonant);
16
}
Pass by Reference (Example)
#include <stdio.h>
void fnFun1(int, int*);
//function prototype
int main(void)
{
int iA=5,iB=10;
printf("Before fun 1\n”);
printf(“iA = %d iB = %d”,iA,iB);
fnFun1(iA, &iB);
//function call
printf(“\n\nAfter fun 1\n”);
printf(“iA = %d iB = %d\n”,iA,iB);
return 0;
}
void fnFun1(int iAA, int * iBB)//function definition
{
iAA++;
*iBB--;
printf("\n\nInside fun 1\n”);
printf(“iAA = %d iBB = %d”,iAA,iBB);
}
UniMAP SemI-11/12
EKT150
Output
Before fun 1
iA=5 iB = 10
Inside fun 1
iAA = 6 iBB = 9
After fun 1
iA = 5 iB = 9
17
Recursive Functions
Recursion is a term describing functions which are called by
themselves (functions that call themselves)
Recursive function has two parts i.e. base case and not base
case
If not base case, the function breaks the problem into a slightly
smaller, slightly simpler, problem that resembles the original
problem and
Launches a new copy of itself to work on the smaller
problem, slowly converging towards the base case
Makes a call to itself inside the return statement
Eventually the base case gets solved and then that value works
its way back up to solve the whole problem
Recursion is very useful in mathematical calculations and in
sorting of lists
UniMAP SemI-11/12
EKT150
18
Recursive Functions
Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
Recursive relationship:
( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
Base case (1! = 0! = 1)
UniMAP SemI-11/12
EKT150
19
Recursive Functions(Example)
Factorial
4 * 6 = 24 is returned
Factorial(4)
4*
3 * 2 = 6 is returned
Factorial(3)
3*
Factorial(2)
2*
2 * 1 = 2 is returned
Factorial(1)
Value 1 is returned
1
UniMAP SemI-11/12
EKT150
20
Recursive Functions(Example)
#include <stdio.h>
int fnFactorial(int);
void main()
{
int iN=4;
printf(“Factorial %d
}
is %d“,n, fnFactorial(n));
int fnFactorial(int iN)
{
if(iN <= 1) //base case
return 1;
else
return ( iN * fnFactorial(iN-1));
}
UniMAP SemI-11/12
EKT150
Call function
name itself
21
Recursive Functions (Example)
Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
Each number is the sum of two previous numbers
Example of a recursive formula:
fib(n) = fib(n-1) + fib(n-2)
UniMAP SemI-11/12
EKT150
22
Recursive Functions (Example)
Diagram of Fibonacci function:
f( 3 )
return
return
f( 1 )
return 1
UniMAP SemI-11/12
f( 2 )
+
+
f( 0 )
f( 1 )
return 1
return 0
EKT150
23
Recursive Functions (Example)
Sample code for fibonacci function
long fnFibonacci( long lN )
{
if ( lN == 0 || lN == 1 ) //base case
return lN;
else
return fnFibonacci( lN - 1 ) +
fnFibonacci( lN – 2 );
}
UniMAP SemI-11/12
EKT150
24
End Week 6 – Functions (2)
Q & A!
UniMAP SemI-11/12
EKT150
25