CProg 1 Chapter 5
CProg 1 Chapter 5
METHODS
Lesson 1: Basic on Methods
Video Reference: Function / Methods In C Programming Language:
https://youtu.be/X7auVd3QpTM
Terminology
Formal Parameter : A variable and its type as they appear in the prototype
of the function or method.
Actual Parameter : The variable or expression corresponding to a formal
parameter that appears in the function or method call in the calling
environment.
1. Pass By Value : This method uses in-mode semantics. Changes made to
formal parameter do not get transmitted back to the caller. Any
modifications to the formal parameter variable inside the called function or
method affect only the separate storage location and will not be reflected
in the actual parameter in the calling environment. This method is also
called as call by value.
Example:
#include <stdio.h>
37 | P a g e
void func(int a, int b)
{ a += b;
printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{ int x = 5, y = 7;
Output:
In func, a = 12 b = 7 In main, x = 5 y = 7
// C program to illustrate
// call by reference #include <stdio.h> void swapnum(int* i, int* j)
{ int temp = *i; *i = *j;
*j = temp;
}
int main(void)
{
int a = 10, b = 20;
// passing parameters
swapnum(&a, &b);
Output:
a is 20 and b is 10
Lesson 3: Recursion
Number Factorial
#include <stdio.h>
When the above code is compiled and executed, it produces the following
result −
Factorial of 12 is 479001600
39 | P a g e
Fibonacci Series
The following example generates the Fibonacci series for a given number
using a recursive function −
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) { return 0;
} if(i == 1) { return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
for (i = 0; i < 10; i++) { printf("%d\t\n", fibonacci(i));
}
return 0;
}
When the above code is compiled and executed, it produces the following
result −
0
1
1
2
3
5
8
13
21
34
40 | P a g e