BCSC 1102 Introduction to Programming Lecture 8
BCSC 1102 Introduction to Programming Lecture 8
Contents
1 Introduction to Functions 2
1
1 Introduction to Functions
Definition: A function is a block of code that performs a specific task.
Advantages:
• Code Reusability
• Better Organization
• Easier Debugging
Example:
1 # include < stdio .h >
2
3 void sayHello () {
4 printf (" Hello , World !\ n ") ;
5 }
6
7 int main () {
8 sayHello () ; // Function call
9 return 0;
10 }
Listing 1: Simple Function Example
3 // Function Declaration
4 void greet () ;
5
6 // Function Definition
7 void greet () {
8 printf (" Greetings !\ n ") ;
9 }
10
11 int main () {
12 greet () ; // Function Call
13 return 0;
2
14 }
Listing 2: Function Declaration, Definition, and Calling
8 int main () {
9 int x = 10;
10 increment ( x ) ;
11 printf (" Outside function : % d \ n " , x ) ; // Original
value remains unchanged
12 return 0;
13 }
Listing 3: Pass by Value
3
• This allows the function to modify the actual arguments.
Example: By Reference
1 # include < stdio .h >
2
8 int main () {
9 int x = 10;
10 increment (& x ) ;
11 printf (" Outside function : % d \ n " , x ) ; // Original
value is modified
12 return 0;
13 }
Listing 4: Pass by Reference
3 void display () {
4 int a = 5; // Local variable
4
5 printf (" Local a : % d \ n " , a ) ;
6 }
7
8 int main () {
9 display () ;
10 // printf ("% d " , a ) ; // Error : a is not accessible
here
11 return 0;
12 }
Listing 5: Local Scope
Example: Global Scope
1 # include < stdio .h >
2
5 void display () {
6 printf (" Global variable : % d \ n " , globalVar ) ;
7 }
8
9 int main () {
10 display () ;
11 printf (" Global variable in main : % d \ n " , globalVar )
;
12 return 0;
13 }
Listing 6: Global Scope
Example: Static Variables (Lifetime)
1 # include < stdio .h >
2
3 void count () {
4 static int num = 0; // Static variable
5 num ++;
6 printf (" Count : % d \ n " , num ) ;
7 }
8
9 int main () {
10 count () ;
11 count () ;
12 count () ;
13 return 0;
14 }
Listing 7: Static Variables