You are on page 1of 22

PGT 106 - C Programming 1

FUNCTIONS
(PART 2)
Chapter 4
Outline
2

 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
 Passing parameters in functions : Pass by reference
 Recursive function
Sample application
3

 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

Think!! Which
What argument
function returns no
names do I want
value and which
to feed in as
function returns a
parameters and
value.
what to return??
Local Variable vs. Global Variable
4
#include <stdio.h> float fnDeterminePrice(int iItemCode)
void fnMenu(); {
float fnDeterminePrice(int); float fPricing;
float fnCalc(float,int); switch(iItemCode)
Code Item Price
void fnPrintResult(float); { 1 Papaya 1.00
case 1:fPricing = 1.00;break; 2 Melon 2.00
int main() case 2:fPricing = 2.00;break; 3 Durian 3.00
{ case 3:fPricing = 3.00;break; Others 4.00
int iCode,iQty; Enter item code and quantity: 1 3
Local variable default:fPricing = 4.00; Payment is 3.00
float fPrice,fPay; }
fnMenu(); return(fPricing);
printf("Enter item code and quantity: "); }
scanf("%d %d", &iCode,&iQty); float fnCalc(float fItemPrice, int iQuantity)
fPrice = fnDeterminePrice(iCode);
{
fPay = fnCalc(fPrice,iQty);
float fTotal;
fnPrintResult(fPay);
return 0; fTotal = fItemPrice*iQuantity;
} return(fTotal);
void fnMenu() }
{ void fnPrintResult(float fPayment)
printf("Code\tItem\tPrice\n"); {
printf("1\tPapaya\t1.00\n"); printf("Payment is %.2f\n", fPayment);
printf("2\tMelon\t2.00\n"); }
printf("3\tDurian\t3.00\n");
printf("\tOthers\t4.00\n");
}
Local Variable vs. Global Variable
5
#include <stdio.h> float fnDeterminePrice(int iCode)
void fnMenu(); {
float fnDeterminePrice(int); switch(iCode)
float fnCalc(float,int); {
void fnPrintResult(float); case 1:fPrice=1.00;break;
int iCode,iQty; case 2:fPrice=2.00;break;
Global variable
float fPrice,fPay; case 3:fPrice=3.00;break;
int main() default:fPrice=4.00;
{ }
fnMenu(); return(fPrice);
Output:
printf("Enter item code and quantity:"); } Code Item Price
scanf("%d %d", &iCode,&iQty); float fnCalc(float fPrice,int iQty) 1 Papaya 1.00
fPrice= fnDeterminePrice(iCode); { 2 Melon 2.00
3 Durian 3.00
fPay=fnCalc(fPrice,iQty); fPay=fPrice*iQty; Others 4.00
fnPrintResult(fPay); return(fPay); Enter item code and quantity: 3 3
return 0; } Payment is 9.00
} void fnPrintResult(float fPay)
void fnMenu( ) {
{ printf("Payment is %.2f\n", fPay);
printf("Code\tItem\tPrice\n"); }
printf("1\tPapaya\t1.00\n");
printf("2\tMelon\t2.00\n"); Global variable can be used by any statements that are
printf("3\tDurian\t3.00\n"); being executed in the system
printf("\tOthers\t4.00\n");
}
Pass by Value
6

 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
Pass by Value (Example)
7

#include <stdio.h>
void fnFun1(int,int); //function prototype Output
int main(void) Before fnFun 1
{ iA = 5 iB = 10
int iA=5, iB=10;
printf("Before fun 1\n"); Inside fnFun 1
printf(" iA = %d iB = %d\n", iA,iB); iAA = 6 iBB = 9
fnFun1(iA, iB); //function call
printf("\nAfter fun 1\n"); After fnFun 1
printf(" iA = %d iB = %d\n", iA,iB);
iA = 5 iB = 10
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);
}
Functions that return more than one value
8

 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

 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
Functions that return more than one value
(Sample application)
9

 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
Functions that return more than one value
(Sample application)
10

#include <stdio.h> void fnReadMarks(float *fM1,float *fM2)


void fnReadMarks(float*,float*); {
float fnCalcAvg(float,float); printf("Enter marks for test1 and test2 : ");
void fnPrint(float); scanf("%f %f", fM1,fM2);
}
Function that returns
int main(void) float fnCalcAvg(float fM1, float fM2) more than one value -
{ { arguments are passed
float fMarks1, fMarks2, fAvg; return((fM1 + fM2)/2); by reference
fnReadMarks(&fMarks1,&fMarks2); }
fAvg = fnCalcAvg(fMarks1,fMarks2); void fnPrint(float fAverage)
fnPrint(fAvg); {
return 0; printf("\nAverage marks are :%.2f\n",fAverage);
} }

Output
Enter marks for test1 and test2 : 70 80
Average marks are : 75.00
Pass by Reference
11

 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
Pass by Reference
12

 Syntax:
 In function prototype 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);
 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
Pass by Reference (Sample Application)
13

 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
Pass by Reference (Example)
14
#include <stdio.h> void fnFindCountVC(char cCh1, int *iVowel, int *iConsonant)
#include <string.h> {
Enter character : A
char fnRead(); switch(cCh1) Do you want to continue? Y
void fnFindCountVC(char, int*, int*); { Enter character : R
void fnPrint(int,int); case 'A': *iVowel = *iVowel +1;break; Do you want to continue? Y
case 'a': *iVowel = *iVowel +1;break; Enter character : e
int main() case 'E': *iVowel = *iVowel +1;break; Do you want to continue? Y
Enter character : z
{ case 'e': *iVowel = *iVowel +1;break; Do you want to continue? N
char cCh, cChoice; int iCountV=0, iCountC=0; case 'I': *iVowel = *iVowel +1;break; Number of vowel : 2
do case 'i': *iVowel = *iVowel +1;break; Number of consonant : 2
{ case 'O': *iVowel = *iVowel +1;break;
cCh = fnRead(); case 'o': *iVowel = *iVowel +1;break;
fnFindCountVC(cCh, &iCountV, &iCountC); case 'U': *iVowel = *iVowel +1;break;
printf("Do you want to continue? "); case 'u': *iVowel = *iVowel +1;break;
scanf("%c", &cChoice); default: *iConsonant = *iConsonant + 1;
getchar(); }
}while((cChoice == 'y') ||(cChoice =='Y')); }
fnPrint(iCountV,iCountC); void fnPrint(int iVowel, int iConsonant)
return 0; {
} Functions printf("Number of vowel : %d\n", iVowel);
char fnRead() that “return” printf("Number of consonant : %d\n", iConsonant);
{ more than }
char cCh1; one value i.e.
printf("Enter character : "); arguments
scanf("%c", &cCh1); are passed
getchar(); by reference
return(cCh1);
}
Pass by Reference (Example)
15

#include <stdio.h>
void fnFun1(int, int*); //function prototype Output
int main(void)
Before fun 1
{
int iA=5,iB=10; iA=5 iB = 10
printf("Before fun 1\n");
printf("iA = %d iB = %d",iA,iB); Inside fun 1
fnFun1(iA, &iB); //function call iAA = 6 iBB = 9
printf("\n\nAfter fun 1\n");
printf("iA = %d iB = %d\n",iA,iB);
After fun 1
return 0;
} iA = 5 iB = 9
void fnFun1(int iAA, int *iBB) //function definition
{
iAA++; Put (*) before the variable
(*iBB)--;
printf("\n\nInside fun 1\n");
printf("iAA = %d iBB = %d",iAA,*iBB);
}
Recursive Functions
16

 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
Recursive Functions
17

 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)
Recursive Functions (Example
18

 Factorial

4 * 6 = 24 is returned
Factorial(4)

4* Factorial(3) 3 * 2 = 6 is returned

3* Factorial(2)
2 * 1 = 2 is returned

2* Factorial(1)

Value 1 is returned
1
Recursive Functions (Example)
19

#include <stdio.h>
int fnFactorial(int);

void main()
{
int N = 4;
printf("Factorial %d is %d",N, fnFactorial(N));
}

int fnFactorial(int iN) Call function


{ name itself
if(iN <= 1) //base case
return 1;
else
return ( iN * fnFactorial(iN-1));
}
Recursive Functions (Example)
20

 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)
Recursive Functions (Example)
22

 Sample code for fibonacci function


#include <stdio.h>
int fnFibonacci( int lN );

void main()
{
int N = 4;
printf("Fibonacci %d is %d",N, fnFibonacci(N));
}
int fnFibonacci( int lN )
{
if ( lN == 0 || lN == 1 ) //base case
return lN;
else

return fnFibonacci ( lN -1) + fnFibonacci( lN-2);


}
PGT 106 - C Programming 23

Q&A

You might also like