Вы находитесь на странице: 1из 44

1

Functions (Part 1)
2

Outline
 Introduction
 Functions in C
Pre-defined functions
User-defined functions
 Number, order and type of parameter
 Functions that do not return a value
 Functions that return a value
3

Why use functions?


Let say you want to print one row of number 3 and one row
of number 5.
#include <stdio.h>
int main()
{
int i, j;
//print one row of number 3
for(i=1; i<=10; i++)
printf(“3");
//print one row of number 5
for(j=1; j<=10; j++)
printf(“5“);
return 0;
}
4

Why use functions?


It seems that you are doing the same thing twice!!
i.e. printing two rows of numbers  encourages re-use of
code
This is wasting time and not flexible!!
Break a large problem into smaller pieces
Smaller pieces sometimes called ‘modules’ or
‘subroutines’ or ‘procedures’ or functions
5 Why use functions?
#include <stdio.h>
void display(int); //function prototype
int main(){
display(8); //function call
display(9); //function call
return 0;
}
void display(int value)// function definition
{
int i;
for(i=1; i<=10; i++){
printf("%d", value);
}
}
6

Functions in C
Functions can be created to execute small,
frequently-used tasks
All C programs consist of one or more functions.
One function must be called main.
In C, there are two types of function
Predefined functions / standard functions
- main(), printf(), scanf()
User-defined functions
- Your own code
7

Predefined Functions (Library)

•Predefined functions are already available


functions that can be used, called library
•The usage is like stdio.h, in which the library name
must be #included at the top of the source code
(preprocessor directive)
•Common libraries :
lstdio.h : printf(), scanf(),
lmath.h : sin(), cos(), exp(), pow(), sqrt(),
lstring.h : strcmp(), strcpy(), strlen(),
lstdlib.h : abs(), fabs()
8
Predefined Functions (Library) -
Example
#include <stdio.h>
#include <math.h> To compile in ubuntu;
#include <string.h> gcc filename.c -lm
void main()
{
char name[30];
int num, num_square,length;
Copy
“Marina”  strcpy(name, “Marina”);
to variable  length = strlen(“Steve”); Measure length
name of word “Steve”
 num_square = pow(num,2);

}
Find the square
of num
9

User-Defined Functions

What do we need to define and make use of


user-defined functions?
1.Function prototypes
2.Function definitions
3.Function calls
10

1. Function Prototypes
•Function prototype is a declaration; indicates
the function exists
•Should have function name, return type and
parameter
•Argument name is not compulsory
•Function prototype has the following form:
<return_type> <function_name> (arg_type arg_name, ...);
e.g. double product (double x,double y);
double product(double,double); //is also
acceptable
Functions Prototype - Example
#include <stdio.h>
Function prototype /* function prototype */
float product(float x, float y);
 Like a variable declaration
 Placed before main () int main()
 Tells compiler that the {
function will be defined later float var1 = 3.0, var2 = 5.0;
 Helps detect program errors float ans;
 Note semicolon!! /*function call*/
ans = product(var1, var2);

printf("var1*var2 = %.2f\n",ans);
}
/* function definition */
float product(float x, float y)
{
float result;
result = x * y;
return result;
}
12

2. Function Calls
•Consists of a function name followed by an
argument expression list enclosed in
parentheses
•Function call has the following form:
<function_name> (exp, exp ...)
•exp is an expression – can be variable or
constant
ans = product(x,y);
Functions Call- Example
#include <stdio.h>
/* function prototype */
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
Function call
/*function call*/
main() is the 'calling ans = product(var1, var2);
function' printf("var1 = %.2f\n"
product() is the 'called "var2 = %.2f\n",var1,var2);
function' printf("var1*var2 = %g\n", ans);
Control transferred to the }
function code /* function definition */
Code in function definition is double product(double x, double y)
executed {
double result;
result = x * y;
return result;
}
14

3. Function Definitions
•Function definition includes the body of a function
•Function definition has the following form:
<return_type> <function_name> (arg_type arg_name, ...)
{
… statements …
}
Example: no semicolon
int sum (int num1,int num2){
int add;
add = num1 + num2; argument name in
function definition
return add; must be included
} in function header
Functions Definition - Example
#include <stdio.h>
/* function prototype */
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
/*function call*/
ans = product(var1, var2);
printf("var1 = %.2f\n"
"var2 = %.2f\n",var1,var2);
printf("var1*var2 = %g\n", ans);
}
Function definition /* function definition */
double product(double x, double y)
Note, NO semicolon {
double result;
result = x * y;
return result;
}
Functions Return - Example
#include <stdio.h>
/* function prototype */
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
Function return /*function call*/
ans = product(var1, var2);
return statement terminates printf("var1 = %.2f\n"
execution of the current function "var2 = %.2f\n",var1,var2);
Control returns to the calling printf("var1*var2 = %g\n", ans);
function }
return expression;
then value of expression is /* function definition */
returned as the value of the double product(double x, double y)
function call {
Only one value can be double result;
returned this way result = x * y;
return result;
}
17

Another Example of Function


//This program sums up two numbers
#include <stdio.h>
int sum(int, int); //function prototype

int main(){
int x,y, result;
printf( “Enter x and y : ”);
scanf(“%d %d”, &x, &y);
result = sum(x,y); //function call
printf(“Sum is : %d”, result);
return 0;
}
int sum(int num1, int num2) //function definition
{
int add;
add = num1+num2;
return add;
}
18
What about number, order and
type of parameter?
•Number, order and type of parameters in the argument
list of a function call and function definition MUST
match.
•If function prototype and definition have three
parameters then the function call must have three
parameters.
•If the types are int, float and double in the
prototype, the types in the function call should be int,
float and double, respectively.
19

Example 1: Number, order and type of


parameter

Example :
 There are two arguments for function prototype, function
definition and function call;
 The first is int and the second is double.
 With these three we have met the number, order and
type requirements.
20
Example 2: Number, order and
type of parameter
int sum(int, int);//function prototype
int sum(int num1, int num2)//function
definition
sum(x,y); //function call

Number, order and type parameter are met:


There are two parameters, the parameters are listed in order
respectively and first parameter is int and second parameter is int.
21
Functions that DO NOT
RETURN a value
//This program sums up two numbers
#include <stdio.h>
void sum_print(int, int); //function prototype
void function1(); //function prototype

int main(){
int x,y;
function1(); //function call
printf(“Enter x and y: ”);
scanf(“%d %d”, &x, &y);
sum_print(x,y); //function call
return 0;
}
void sum_print(int num1, int num2){ //function definition
int add;
add = num1+num2;
printf(“Sum is: %d”,add);
}
void function1(){ //function definition
printf(“Welcome to this program\n”);
}
22

Functions that RETURN a value


//This program sums up two numbers
#include <stdio.h>
int sum(int,int); //function prototype
int main(){
int x,y,result;
printf(“Enter x and y: ”);
scanf(“%d %d”, &x, &y);
result = sum(x,y); //function call
printf(“Sum is : %d”,result);
return 0;
}
int sum(int num1, int num2){ //function definition
int add;
add = num1+num2;
return add;
}
Function Call as Logical Expression
 Function call used as logical expression
int calc(int,int); //function prototype
void main(void){
int num1, num2;
scanf(“%d %d”,&num1,&num2);
if(calc(num1,num2)>100) //function call used as logical expression
printf(“result greater than 100”);
else
printf(“result less than 100”);
}
int calc(int n1,int n2) {
int answer;
answer=n1+n2;
return answer;
}
24

Function Call in printf Statement


Function call used in printf statement
int calc(int,int); //function prototype
void main(void){
int num1,num2;
scanf(“%d %d”,&num1,&num2);
//function call returns a value and puts in printf
printf(“Answer : %d”,calc(num1, num2) );
}
int calc(int n1,int n2) {
int answer;
answer=n1+n2;
return(answer);
}
25

Naming Convention in Function


Rules regarding naming convention for variables num1 passes value to n1,
num2 passes value to n2.
Better use different variable names for parameters in main AND
parameters in function definition

int calc(int,int); //prototype function


void main(void){
int num1,num2,result; //declare like this
scanf(“%d %d”,&num1,&num2);
result = calc(num1,num2); //function call
printf(“jawapan : %d“,result);
}
//function definition
int calc(int n1,int n2) //simply declare like this
{
int answer;
answer=n1+n2;
return(answer);
}
26

Sample application
•Write a C program that calculates and prints
addition and subtraction of numbers.
•Your program should have functions:
ladd : adds two numbers
lsubtract : subtracts two numbers
lprint_result : prints results from calculation
27

Sample application(cont)
#include <stdio.h>
int add(int,int);
int subtract(int,int);
void print_result(int);
int main()
{ int num1,num2,answer;
char op;
printf(“Enter two numbers and operator:”);
scanf(“%d %d %c”, &num1,&num2,&op);
switch(op)
{ case ‘+’ :answer=add(num1,num2);break;
case ‘-’ :answer=subtract(num1,num2);break;
default: printf(“Invalid operator”);
exit(0);
}
print_result(answer);
return 0;
}
int add(int x,int y)
{
int sum;
sum = x+y;
return(sum);
}
int subtract(int x,int y)
{
int sub;
sub=x-y;
return(sub);
}
void print_result(int ans)
{
printf(“Answer is %d”, ans);
}
1 /* Fig. 5.4: fig05_04.c
UniMAP
EKT
28 150 :Sem
Computer
2
I -10/11Programming
Finding the maximum of three integers */
3 #include <stdio.h>
4 1. FUNCTION PROTOTYPE (3
5 int maximum(int, int, int); /* function prototype PARAMETERS)‫‏‬
*/ 6
7 int main()‫‏‬
8 {
9 int a, b, c;
10
11 printf( "Enter three integers: " );
12 scanf( "%d %d %d", &a, &b, &c );
13 printf( "Maximum is: %d\n", maximum( a, b, c )
); 14 2. FUNCTION CALL
15 return 0;
16 }
17
18 /* Function maximum definition */
19 int maximum(int x, int y, int z)‫‏‬
20 {
21 int max = x; 3. FUNCTION DEFINITION
22
23 if ( y > max )‫‏‬
24 max = y;
25
26 if ( z > max )‫‏‬
27 max = z;
28
29 return max;
30 }
Enter three integers: 22 85 17
Maximum is: 85

PROGRAM OUTPUT
29
Scope and Mechanics of Passing Values to
Functions
•Scope refers to the region in which a declaration is
active
•Two types:
Global Variable/ File Scope
Local Variable/ Function Scope
30
Global and Local Variables /*printf(
} Compute
circle
#include
float
main()
float
scanf(“%f”
if
else
} (pi
*/
{
rad;
float
printf(
rad Area
“Area
area
peri =and
<stdio.h>
= “Enter
3.14159;
, /*
>“Negative
“Area
“Peri
0.0 =)
pi
2 *Perimeter
&rad);
the
Local
*radius
/*
%f\n”
={ */
Global
%f\n”
pi
rad , “ of
);
radius\n”);
*
, *
rad;
area
rad;
area
peri a
*/);
);

•Global variable
These variables are declared
outside all functions at the
top of a source file.
declarations not placed in
any functions
Life time of a global variable
is the entire execution period
of the program.
Can be accessed by any
function defined below the
declaration, in a file.
31
Global and Local Variables /*printf(
} Compute
circle
#include
float
main()
float
scanf(“%f”
if
else
} (pi
*/
{
rad;
float
printf(
rad Area
“Area
area
peri
> =and
<stdio.h>
= “Enter
3.14159;
, /*
&rad);
=the
“Area
“Peri
“Negative
0.0 pi
2 *Perimeter
)Local
*radius
/*
%f\n”
={ */
Global
%f\n”
pi
rad , “ of
);
*/
radius\n”);
*
, *rad;
area
rad;
area
peri a
););

•Local variables
These variables are declared
inside some functions (in a block {
… })
Life time is the entire execution
period of the function in which it
is defined.
Cannot be accessed by any
other function  scope is within
its block
In general variables declared
inside a block are accessible only
in that block.
32

Global Variable : Example


#include <stdio.h>

int global = 3; //This is the global variable


void ChangeGlobal( );

void main(void){
printf("%d\n“, global); //Reference to global variable
ChangeGlobal();
printf("%d\n", global);
}

void ChangeGlobal( ){
global = 5; //Reference to global variable
}

The output will be:


3
5
33
Local Variable : Example
#include <stdio.h>

void ChangeLocal();

void main(void){
int local = 3; //This is a local variable
printf("%d\n", local); //Reference to local variable
ChangeLocal();
printf("%d\n", local);
return 0;
}

void ChangeLocal(){
int local = 5; //This is another local variable
printf("%d\n", local);
}
The output will be:
3
5
3
34

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 Think!! Which function returns
parameters and what to no value and which function
return?? returns a value.
35

Sample Application: Local Variables


#include <stdio.h>
void fnMenu();
float fnDeterminePrice(int);
float fnCalc(float,int);
void fnPrintResult(float);
int main()
{ int iCode,iQty;
float fPriceUnit,fPay;
fnMenu();
printf("Enter item code and
quantity:");
scanf("%d %d", &iCode,&iQty);
fPriceUnit =
fnDeterminePrice(iCode);
fPay = fnCalc(fPriceUnit,iQty);
fnPrintResult(fPay);
return 0;
}
36

Sample Application: Local Variables


#include <stdio.h>
void fnMenu()
void fnMenu(); {
float fnDeterminePrice(int); printf("Code\tItem\tPrice\n");
float fnCalc(float,int);
void fnPrintResult(float); printf("1\tPapaya\t1.00\n");
printf("2\tMelon\t2.00\n");
int main() printf("3\tDurian\t3.00\n");
{ int iCode,iQty; printf("\tOthers\t4.00\n");
float fPriceUnit,fPay;
fnMenu(); }
printf("Enter item code and
quantity:");
scanf("%d %d", &iCode,&iQty);
fPriceUnit =
fnDeterminePrice(iCode);
fPay = fnCalc(fPriceUnit,iQty);
fnPrintResult(fPay);
return 0;
}
37

Sample Application: Local Variables


#include <stdio.h>
void fnMenu()
void fnMenu(); {
float fnDeterminePrice(int); printf("Code\tItem\tPrice\n");
float fnCalc(float,int);
void fnPrintResult(float); printf("1\tPapaya\t1.00\n");
printf("2\tMelon\t2.00\n");
int main() printf("3\tDurian\t3.00\n");
{ int iCode,iQty; printf("\tOthers\t4.00\n");
float fPriceUnit,fPay;
fnMenu(); }
printf("Enter item code and
quantity:");
scanf("%d %d", &iCode,&iQty);
fPriceUnit =
fnDeterminePrice(iCode); OUTPUT:
fPay = fnCalc(fPriceUnit,iQty);
Code Item Price
fnPrintResult(fPay);
return 0; 1 Papaya 1.00
} 2 Melon 2.00
3 Durian 3.00
Others 4.00
Sample Application: Local Variables
#include <stdio.h>
void fnMenu();
float fnDeterminePrice(int);
float fnCalc(float,int);
void fnPrintResult(float);
int main()
{ int iCode,iQty;
float fPriceUnit,fPay;
fnMenu();
printf("Enter item code and
quantity:");
scanf("%d %d", &iCode,&iQty);
fPriceUnit =
fnDeterminePrice(iCode); OUTPUT:
fPay = fnCalc(fPriceUnit,iQty);
fnPrintResult(fPay); Code Item Price
return 0; 1 Papaya 1.00
} 2 Melon 2.00
3 Durian 3.00
Others 4.00
Enter item code and quantity: 1 3
39

Sample Application: Local Variables


float fnDeterminePrice(int
#include <stdio.h> iItemCode)
void fnMenu(); {
float fnDeterminePrice(int); float fPricing;
float fnCalc(float,int); switch(iItemCode)
void fnPrintResult(float); {
int main() case 1: fPricing = 1.00;break;
{ int iCode,iQty; case 2: fPricing = 2.00;break;
float fPriceUnit,fPay; case 3: fPricing = 3.00;break;
fnMenu(); default:fPricing = 4.00;
printf("Enter item code and
quantity:"); }
return fPricing;
scanf("%d %d", &iCode,&iQty);
fPriceUnit = }
fnDeterminePrice(iCode);
fPay = fnCalc(fPriceUnit,iQty);
fnPrintResult(fPay);
return 0;
}
40

Sample Application: Local Variables


#include <stdio.h>
void fnMenu();
float fnDeterminePrice(int);
float fnCalc(float,int); float fCalc(float fItemPrice,
void fnPrintResult(float); int iQuality)
int main() {
{ int iCode,iQty; float fTotal;
float fPriceUnit,fPay; fTotal = fItemPrice*iQuantity;
fnMenu();
printf("Enter item code and
quantity:"); return fTotal;
}
scanf("%d %d", &iCode,&iQty);
fPriceUnit =
fnDeterminePrice(iCode);
fPay = fnCalc(fPriceUnit,iQty);
fnPrintResult(fPay);
return 0;
}
41

Sample Application: Local Variables


#include <stdio.h>
void fnMenu();
float fnDeterminePrice(int);
float fnCalc(float,int);
void fnPrintResult(float);
int main()
{ int iCode,iQty; void fnPrintResult(float fPayment)
{
float fPriceUnit,fPay;
fnMenu(); printf("Payment is %.2f\n", fPayment);
printf("Enter item
} code and
quantity:");
scanf("%d %d", &iCode,&iQty);
fPriceUnit = OUTPUT:
fnDeterminePrice(iCode);
Code Item
fPay = fnCalc(fPriceUnit,iQty); Price
fnPrintResult(fPay); 1 Papaya 1.00
return 0; 2 Melon 2.00
} 3 Durian 3.00
Others 4.00
Enter item code and quantity: 1 3
Payment is 3.00
42 Sample Application: Global
Variables
#include <stdio.h>
void fnMenu(); void fnDeterminePrice()
void fnDeterminePrice();
void fnCalc(); {
void fnPrintResult(); switch(iCode)
{
int iCode,iQty; case 1: fPriceUnit=1.00;
float fPriceUnit,fPay;
break;
int main() case 2: fPriceUnit=2.00;
{ break;
fnMenu(); case 3: fPriceUnit=3.00;
printf("Enter item code and
quantity:"); break;
default:fPriceUnit=4.00;
scanf("%d %d", &iCode,&iQty);
fnDeterminePrice(); }
fnCalc(); }
fnPrintResult();
return 0;
}
43 Sample Application: Global
Variables
#include <stdio.h>
void fnMenu();
void fnDeterminePrice();
void fnCalc(); void fCalc()
void fnPrintResult(); {
int iCode,iQty;
float fPriceUnit,fPay; fPay = fPriceUnit*iQty;
}
int main()
{
fnMenu();
printf("Enter item code and
quantity:");
scanf("%d %d", &iCode,&iQty);
fnDeterminePrice();
fnCalc();
fnPrintResult();
return 0;
}
44 Sample Application: Global
Variables
#include <stdio.h>
void fnMenu();
void fnDeterminePrice();
void fnCalc();
void fnPrintResult();
void fnPrintResult()
int iCode,iQty; {
float fPriceUnit,fPay;
printf("Payment is %.2f\n", fPay);
int main() }
{
fnMenu();
printf("Enter item code and
quantity:"); OUTPUT:
scanf("%d %d", &iCode,&iQty);
fnDeterminePrice(); Code Item Price
fnCalc(); 1 Papaya 1.00
fnPrintResult(); 2 Melon 2.00
return 0; 3 Durian 3.00
} Others 4.00
Enter item code and quantity: 1 3
Payment is 3.00

Вам также может понравиться