Академический Документы
Профессиональный Документы
Культура Документы
• Motivation—why needed
• Examples
Introduction to Functions • How two functions communicate
• void functions
Structured Programming • Function parameters
• Function returning values
(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and
from C Teach Yourself, 3rd editions, by Herbert Shiield)
• Local variable concept and scope rule
• Function prototypes & Header files
Introduction to Functions 1 Introduction to Functions 2
Ashikur Rahman
1
8/8/2020
2
8/8/2020
• Benefits main(){
printf("I ");
– Divide and conquer printf("Like ");
• Manageable program development printf("C");
}
– Software reusability
• Use existing functions as building blocks for new
programs OUTPUT: I C
Like C
– Avoids code repetition
3
8/8/2020
Example Example
LIKE(){ LIKE(){
main(){ main(){
printf("I "); printf("I ");
LIKE(); LIKE();
printf("C"); printf("C");
} }
OUTPUT: I C
Like C OUTPUT: I Like C
4
8/8/2020
printf("Like ");
}
Through
main(){ Caller Callee
int i; Function Parameters Function
printf("I "); (for example (for example
for(i = 1; i <= 5; i++)
main ) LIKE )
LIKE();
By returning
printf("C");
}
Values
OUTPUT: I Like C
Like Like Like Like C
5
8/8/2020
6
8/8/2020
OUTPUT: 4
7
8/8/2020
8
8/8/2020
9
8/8/2020
10
8/8/2020
main(){ main(){
main(){ main(){
int p;
min(3,4); int x,y,p; int p;
p = min(3,4);
printf("%d\n",r); scanf("%d%d",&x,&y); scanf("%d%d",&a,&b);
printf("%d\n",p);
} p = min(x,y); p = min(a,b);
}
printf("%d\n",p); printf("%d\n",p);
} }
11
8/8/2020
12
8/8/2020
A(){
…..
….
….
}
Ashikur Rahman Introduction to Functions 25 Ashikur Rahman Introduction to Functions 26
13
8/8/2020
14
8/8/2020
15
8/8/2020
16
8/8/2020
Solution
Solution diagram int numberofDays(int year){
int days;
if (year%400 == 0)
days = 366;
else if (year%100 == 0)
days = 365;
year numberofDays else if (year%4 == 0)
days
days = 366;
else days = 365;
return days;
}
void main(void){
int y,p;
return-type function-name (parameter declarations) { scanf("%d",&y);
p = numberofDays(y);
definitions and statements
printf("Number of days %d\n",p);
} if(p == 366) printf("LEAP YEAR");
else printf("Not a Leap Year ");
Introduction to Functions 33 } Introduction to Functions 34
Ashikur Rahman Ashikur Rahman
17
8/8/2020
18
8/8/2020
19
8/8/2020
Solution
Solution diagram int findMax(int x[], int n){
int i, max;
max = x[0];
for(i = 1; i < n; i++){
if (max < x[i])
max = x[i];
Number set findMax }
Max value
return max;
}
void main(void){
int a[] = {34, 21, 65, 78, 90};
int b[] = {4, 2, 8};
return-type function-name (parameter declarations) { int r;
findMax(a);
r = findMax(a,5);
definitions and statements printf("%d\n", r);
} r = findMax(b,3);
findMax(b);
printf("%d", r);
Introduction to Functions 39 } Introduction to Functions 40
Ashikur Rahman Ashikur Rahman
20
8/8/2020
Questions?
Introduction to Functions 41
21