SlideShare a Scribd company logo
Dr. Amna Ali A Mohamed
Faculty of Information Technology
Chapter 2: function & recursion
Introduction to Functions
• What is a Function?
• A function is a block of code that performs a specific task.
• It provides modularity and reusability in programming.
• Why Use Functions?
• Breaks down complex tasks into smaller, manageable tasks.
• Avoids code duplication.
• Improves readability and maintainability.
Introduction to Functions
• Defining a Function
return_type function_name(parameter_list) {
// Function body
}
• Example:
int add(int x, int y) {
int z; z = x + y;
return z;
}
• Explanation:
• int is the return type.
• add is the function name.
• int x, int y are the parameters.
• The function returns the sum of x and y.
Calling a Function
Syntax:
#include <stdio.h>
int add(int x, int y) {
return x + y;
}
int main() {
int a = 10, b = 20, result;
result = add(a, b); // Function call
printf("Sum: %dn", result);
return 0;
}
Explanation:
• The add function is called with arguments a and b.
• The result is stored in result and printed.
function_name(arguments);
• Example:
Parameter Passing
• Pass by Value:
• The value of the actual parameter is copied to the formal parameter.
• Changes to the formal parameter do not affect the actual parameter.
#include <stdio.h>
void increment(int x) {
x++;
printf("Inside function: %dn", x);
}
int main() {
int a = 10;
increment(a); // Pass by value
printf("Outside function: %dn", a);
return 0;
}
• Explanation:
• The value of a is copied to x.
• Changes to x do not affect a.
Call by Reference
• Pass by Reference:
• The address of the actual parameter is passed to the formal parameter.
• Changes to the formal parameter affect the actual parameter.
• Example:
#include <stdio.h>
void increment(int *x) {
(*x)++;
printf("Inside function: %dn", *x);
}
int main() {
int a = 10;
increment(&a); // Pass by reference
printf("Outside function: %dn", a);
return 0;
}
Explanation:
•The address of a is passed to x.
•Changes to *x affect a.
Passing Arrays to Functions
How to Pass Arrays?
• Pass the array name (which is a pointer to the first element of the array).
• The size of the array is usually passed as an additional parameter.
Passing a 1D Array to a Function Syntax:
return_type function_name(data_type array[], int
size);
Call by Reference
Passing a 1D Array to a Function example
#include <stdio.h>
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); } printf("n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printArray(arr, size); // Pass array to function
return 0;
}
Explanation:
•The array arr is passed to the function printArray.
•The function processes each element of the array.
Modifying a 1D Array in a Function example
#include <stdio.h>
void incrementArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
arr[i] += 1; // Modify each element of the array
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
incrementArray(arr, size); // Pass array to function
printf("Modified Array:n");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("n");
return 0;
}
Explanation:
• The function incrementArray modifies each element of the array.
• Changes are reflected in the original array.
Passing a 2D Array to a Function
Syntax: return_type function_name(data_type array[][cols], int rows);
#include <stdio.h>
void printMatrix(int mat[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", mat[i][j]);
}
printf("n");
}
}
int main() {
int mat[2][3] = {{1, 2, 3}, {4, 5, 6}};
printMatrix(mat, 2); // Pass 2D array to function
return 0;
Explanation:
•The 2D array mat is passed to the function printMatrix.
•The function processes each element of the 2D array.
Passing Arrays to Functions using pointer
Why Use Pointers with Arrays?
• Pointers provide direct access to memory locations, making array manipulation efficient.
• Passing arrays to functions using pointers avoids copying the entire array.
•Key Concepts:
• Array name is a pointer to the first element of the array.
• Pointer arithmetic can be used to traverse arrays.
Passing Arrays to Functions using pointer
Syntax:
return_type function_name(data_type *array, int size);
#include <stdio.h>
void printArray(int *arr, int n) {
for (int i = 0; i < n; i++) {
printf("%d ", *(arr + i)); // Access array elements using pointer arithmetic
}
printf("n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printArray(arr, size); // Pass array using pointer
return 0;
}
Example:
Explanation:
• The array arr is passed as a pointer to the
function printArray.
• Pointer arithmetic (*(arr + i)) is used to
access array elements.
Passing Structures to Functions
• How to Pass Structures?
Pass by value (a copy of the structure is passed).
Pass by reference (a pointer to the structure is passed).
• Passing a Structure by Value
Syntax
:
return_type function_name(struct structure_name variable);
Passing a Structure by Value example:
Passing Structures to Functions
#include <stdio.h>
struct Student {
char name[50];
int rollNo;
float marks;
};
void printStudent(struct Student s) {
printf("Name: %sn", s.name);
printf("Roll No: %dn", s.rollNo);
printf("Marks: %.2fn", s.marks);
}
int main() {
struct Student student1 = {"John Doe", 101,
95.5};
printStudent(student1); // Pass by value
return 0;
}
Explanation:
• A copy of the structure student1 is passed to the
function printStudent.
• Changes to the structure inside the function do not
affect the original structure.
Passing Structures to Functions
Passing a Structure by Reference
Syntax:
return_type function_name(struct structure_name *variable);
Passing Structures to Functions
Passing a Structure by Reference example
#include <stdio.h>
struct Student {
char name[50];
int rollNo;
float marks;
};
void updateMarks(struct Student *s) {
s->marks += 10; // Modify the structure using a
pointer
}
int main() {
struct Student student1 = {"John Doe", 101, 95.5};
updateMarks(&student1); // Pass by reference
printf("Updated Marks: %.2fn", student1.marks);
return 0;
}
Explanation:
• The address of the structure student1 is passed to
the function updateMarks.
• Changes to the structure inside the function affect
the original structure.
Passing Structures to Functions
Passing an Array of Structures to Functions
Why Pass an Array of Structures?
• To process multiple records of structured data within a function.
• Useful for operations like sorting, searching, or updating.
How to Pass an Array of Structures?
• Pass the array name (which is a pointer to the first element of the array).
Syntax:
return_type function_name(struct structure_name array[], int size);
Passing an Array of Structures to Functions example:
#include <stdio.h>
struct Student {
char name[50];
int rollNo;
float marks;
};
void printStudents(struct Student students[], int n) {
for (int i = 0; i < n; i++) {
printf("Student %d:n", i + 1);
printf("Name: %sn", students[i].name);
printf("Roll No: %dn", students[i].rollNo);
printf("Marks: %.2fn", students[i].marks);
}
}
int main() {
struct Student students[3] = {
{"Alice", 101, 95.5},
{"Bob", 102, 88.0},
{"Charlie", 103, 92.5} };
printStudents(students, 3); // Pass array of structures
return 0;
}
Explanation:
• The array students is passed to the function printStudents.
• The function processes each element of the array.
Modifying an Array of Structures in a
Function example:
#include <stdio.h>
struct Student {
char name[50];
int rollNo;
float marks;
};
void updateMarks(struct Student students[], int n) {
for (int i = 0; i < n; i++) {
students[i].marks += 10; // Update marks for each student
}
}
int main() {
struct Student students[3] = {
{"Alice", 101, 95.5},
{"Bob", 102, 88.0},
{"Charlie", 103, 92.5}
};
updateMarks(students, 3); // Pass array of structures
printf("Updated Marks:n");
for (int i = 0; i < 3; i++) {
printf("Name: %s, Marks: %.2fn", students[i].name,
students[i].marks);
}
return 0;
Explanation:
• The function updateMarks modifies
the marks of each student in the array.
• Changes are reflected in the original array.
Introduction to Recursion
How Recursion Works (Stack Mechanism)
Recursion and the Call Stack:
Each recursive call creates a new stack frame.
The stack grows until the base case is reached.
Once the base case is reached, the stack unwinds, and results are returned.
Example: Factorial of 3
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
int main()
{
int n = 3;
printf("Factorial of %d is %dn", n, factorial(n));
return 0;
}
Factorial (N!)
• N! = (N-1)! * N [for N > 1]
• 1! = 1
• 3!
= 2! * 3
= (1! * 2) * 3
= 1 * 2 * 3
• Recursive design:
• Decomposition: (N-1)!
• Composition: * N
• Base case: 1!
Factorial example
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n- 1); // Recursive case
}
int main()
{
int n = 5;
printf("Factorial of %d is %dn", n, factorial(n));
return 0;
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * factorial(2); // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * factorial(2); // Recursive case
}
int factorial(int 2) {
if (n == 0) return 1; // Base case
return 2 * factorial(1); // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * factorial(2); // Recursive case
}
int factorial(int 2) {
if (n == 0) return 1; // Base case
return 2 * factorial(1); // Recursive case
}
int factorial(int 1) {
if (n == 0) return 1; // Base case
return 1 * factorial(0); // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * factorial(2); // Recursive case
}
int factorial(int 2) {
if (n == 0) return 1; // Base case
return 2 * factorial(1); // Recursive case
}
int factorial(int 1) {
if (n == 0) return 1; // Base case
return 2 * factorial(1); // Recursive case
}
int factorial(int 0) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * factorial(2); // Recursive case
}
int factorial(int 2) {
if (n == 0) return 1; // Base case
return 2 * factorial(1); // Recursive case
}
int factorial(int 1) {
if (n == 0) return 1; // Base case
return 1 * factorial(0); // Recursive case
}
int factorial(int 0) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * factorial(2); // Recursive case
}
int factorial(int 2) {
if (n == 0) return 1; // Base case
return 2 * factorial(1); // Recursive case
}
int factorial(int 1) {
if (n == 0) return 1; // Base case
return 1 * 1; // Recursive case
}
int factorial(int 0) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * factorial(2); // Recursive case
}
int factorial(int 2) {
if (n == 0) return 1; // Base case
return 2 * factorial(1); // Recursive case
}
int factorial(int 1) {
if (n == 0) return 1; // Base case
return 1; // Recursive case
}
int factorial(int 0) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * factorial(2); // Recursive case
}
int factorial(int 2) {
if (n == 0) return 1; // Base case
return 2 * factorial(1); // Recursive case
}
int factorial(int 1) {
if (n == 0) return 1; // Base case
return 1; // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * factorial(2); // Recursive case
}
int factorial(int 2) {
if (n == 0) return 1; // Base case
return 2 * 1 // Recursive case
}
int factorial(int 1) {
if (n == 0) return 1; // Base case
return 1; // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * factorial(2); // Recursive case
}
int factorial(int 2) {
if (n == 0) return 1; // Base case
return 2 // Recursive case
}
int factorial(int 1) {
if (n == 0) return 1; // Base case
return 1; // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 3 * 2; // Recursive case
}
int factorial(int 2) {
if (n == 0) return 1; // Base case
return 2 // Recursive case
}
int factorial(int 3) {
if (n == 0) return 1; // Base case
return 6; // Recursive case
}
Fibonacci Numbers
• The Nth
Fibonacci number is the sum of the previous two Fibonacci
numbers
• 0, 1, 1, 2, 3, 5, 8, 13, …
• Recursive Design:
• Decomposition & Composition
• fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
• Base case:
• fibonacci(1) = 0
• fibonacci(2) = 1
Fibonacci Numbers #include <stdio.h>
int fibonacci(int n) {
if (n <= 1) return n; // Base case
return fibonacci(n - 1) + fibonacci(n - 2); // Binary recursive call
}
int main() {
int n = 4;
printf("Fibonacci number at position %d is %dn", n, fibonacci(n));
return 0;
}
Fibonacci Sequence Definition
The Fibonacci sequence is defined as:
• fib(0) = 0
• fib(1) = 1
• fib(n) = fib(n-1) + fib(n-2) for n > 1
For n = 4, the expected Fibonacci number is 3 (since the sequence is: 0, 1, 1, 2, 3).
Fibonacci Numbers
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1) return n; // Base case
return fibonacci(n - 1) + fibonacci(n - 2); // Binary recursive call
}
int main() {
int n = 4;
printf("Fibonacci number at position %d is %dn", n, fibonacci(n));
return 0;
}
Recursive Execution Tree for fibonacci(4)
1.Initial Call: fibonacci(4)
•Since 4 > 1, it calls fibonacci(3) + fibonacci(2).
2.First Subtree: fibonacci(3)
•3 > 1 → Calls fibonacci(2) + fibonacci(1).
•fibonacci(2) → Calls fibonacci(1) + fibonacci(0).
•fibonacci(1) → Returns 1 (base case).
•fibonacci(0) → Returns 0 (base case).
•Result: 1 + 0 = 1.
•fibonacci(1) → Returns 1.
•Result: 1 (from fib(2)) + 1 (from fib(1)) = 2.
3.Second Subtree: fibonacci(2)
•2 > 1 → Calls fibonacci(1) + fibonacci(0).
•fibonacci(1) → Returns 1.
•fibonacci(0) → Returns 0.
•Result: 1 + 0 = 1.
4.Final Sum:
•fibonacci(4) = fibonacci(3) + fibonacci(2) = 2 + 1 = 3.
Fibonacci Numbers #include <stdio.h>
int fibonacci(int n) {
if (n <= 1) return n; // Base case
return fibonacci(n - 1) + fibonacci(n - 2); // Binary recursive call
}
int main() {
int n = 4;
printf("Fibonacci number at position %d is %dn", n, fibonacci(n));
return 0;
}
Visualization of Recursive Calls
fib(4)
= fib(3) + fib(2)
= [fib(2) + fib(1)] + [fib(1) + fib(0)]
= [ (fib(1) + fib(0)) + 1 ] + [1 + 0]
= [ (1 + 0) + 1 ] + 1
= 2 + 1
= 3
Types of Recursion
• Linear Recursion:
• The function makes a single call to itself.
• Example: Factorial calculation.
• Tail Recursion:
• The recursive call is the last operation in the function.
• Example: GCD calculation.
• Binary Recursion:
• The function makes two recursive calls.
• Example: Fibonacci sequence.
• Mutual Recursion:
• Two or more functions call each other.
• Example: Determining if a number is even or odd.
Stack Overheads in Recursion
What are Stack Overheads?
• Each recursive call consumes stack space.
• Excessive recursion can lead to stack overflow.
Example:
#include <stdio.h>
void recursiveFunction(int n) {
if (n == 0)
return;
printf("Depth: %dn", n);
recursiveFunction(n - 1);
}
int main() {
recursiveFunction(5);
return 0;
}
Explanation:
• Each call to recursiveFunction adds a new stack frame.
• The stack grows with each recursive call.
Key Points to Remember
1. Functions provide modularity and reusability.
2. Parameters can be passed by value or by reference.
3. Recursion is a powerful technique but can lead to stack overheads.
4. Tail recursion can be optimized by the compiler.
Exercises
1. Write a recursive function to calculate the sum of digits of a number.
2. Write a program to GCD Calculation Using Recursion
3. Write a recursive function to calculate the power of a number.
4. Write two mutually recursive functions to determine if a number is a multiple of
3 or 5
Solutions
#include <stdio.h>
int sumOfDigits(int n) {
if (n == 0) return 0; // Base case
return (n % 10) + sumOfDigits(n / 10); // Linear recursive call
}
int main() {
int n = 12345;
printf("Sum of digits of %d is %dn", n, sumOfDigits(n));
return 0;
}
Sum of Digits
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) return a; // Base case
return gcd(b, a % b); // Recursive call
}
int main() {
int a = 56, b = 98;
printf("GCD of %d and %d is %dn", a, b, gcd(a, b));
return 0;
}
Recursive Function for GCD Step-by-Step Execution
• Input: a = 56, b = 98
• Step 1: gcd(56, 98)
• b ≠ 0, so call gcd(98, 56 % 98) → gcd(98, 56)
• Step 2: gcd(98, 56)
• b ≠ 0, so call gcd(56, 98 % 56) → gcd(56, 42)
• Step 3: gcd(56, 42)
• b ≠ 0, so call gcd(42, 56 % 42) → gcd(42, 14)
• Step 4: gcd(42, 14)
• b ≠ 0, so call gcd(14, 42 % 14) → gcd(14, 0)
• Step 5: gcd(14, 0)
• b == 0, so return 14 (base case).
• Final Result: 14
#include <stdio.h>
int power(int x, int n) {
if (n == 0) return 1; // Base case
return x * power(x, n - 1); // Binary recursive call
}
int main() {
int x = 2, n = 5;
printf("%d^%d is %dn", x, n, power(x, n));
return 0;
}
Power Calculation
#include <stdio.h>
int isMultipleOf3(int n);
int isMultipleOf5(int n);
int isMultipleOf3(int n) {
if (n == 0) return 1; // Base case
if (n < 0) return 0;
return isMultipleOf5(n - 3); // Mutual recursive call
}
int isMultipleOf5(int n) {
if (n == 0) return 1; // Base case
if (n < 0) return 0;
return isMultipleOf3(n - 5); // Mutual recursive call
}
int main() {
int n = 15;
if (isMultipleOf3(n)) {
printf("%d is a multiple of 3n", n);
} else if (isMultipleOf5(n)) {
printf("%d is a multiple of 5n", n);
} else {
printf("%d is not a multiple of 3 or 5n", n);
}
return 0;
}
Multiple of 3 or 5
Ad

More Related Content

Similar to Lecture_3 the functions parameters andrecursion .pptx (20)

Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
psaravanan1985
 
6. function
6. function6. function
6. function
웅식 전
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
UMA PARAMESWARI
 
Session 4
Session 4Session 4
Session 4
Shailendra Mathur
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
hhliu
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
imtiazalijoono
 
Array Cont
Array ContArray Cont
Array Cont
Ashutosh Srivasatava
 
Function & Recursion
Function & RecursionFunction & Recursion
Function & Recursion
Meghaj Mallick
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
rajatryadav22
 
functions
functionsfunctions
functions
Makwana Bhavesh
 
Functions
FunctionsFunctions
Functions
PralhadKhanal1
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
Emertxe Information Technologies Pvt Ltd
 
Fucntions & Pointers in C
Fucntions & Pointers in CFucntions & Pointers in C
Fucntions & Pointers in C
Janani Satheshkumar
 
Pointers [compatibility mode]
Pointers [compatibility mode]Pointers [compatibility mode]
Pointers [compatibility mode]
Kathmandu University
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
Dr. Chandrakant Divate
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college
2017eee0459
 
USER DEFINE FUNCTION AND STRUCTURE AND UNION
USER DEFINE FUNCTION AND STRUCTURE AND UNIONUSER DEFINE FUNCTION AND STRUCTURE AND UNION
USER DEFINE FUNCTION AND STRUCTURE AND UNION
MSridhar18
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
MKalpanaDevi
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
Gem WeBlog
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
hhliu
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
imtiazalijoono
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
rajatryadav22
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
Dr. Chandrakant Divate
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college
2017eee0459
 
USER DEFINE FUNCTION AND STRUCTURE AND UNION
USER DEFINE FUNCTION AND STRUCTURE AND UNIONUSER DEFINE FUNCTION AND STRUCTURE AND UNION
USER DEFINE FUNCTION AND STRUCTURE AND UNION
MSridhar18
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
MKalpanaDevi
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
Gem WeBlog
 

Recently uploaded (20)

Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Ad

Lecture_3 the functions parameters andrecursion .pptx

  • 1. Dr. Amna Ali A Mohamed Faculty of Information Technology Chapter 2: function & recursion
  • 2. Introduction to Functions • What is a Function? • A function is a block of code that performs a specific task. • It provides modularity and reusability in programming. • Why Use Functions? • Breaks down complex tasks into smaller, manageable tasks. • Avoids code duplication. • Improves readability and maintainability.
  • 3. Introduction to Functions • Defining a Function return_type function_name(parameter_list) { // Function body } • Example: int add(int x, int y) { int z; z = x + y; return z; } • Explanation: • int is the return type. • add is the function name. • int x, int y are the parameters. • The function returns the sum of x and y.
  • 4. Calling a Function Syntax: #include <stdio.h> int add(int x, int y) { return x + y; } int main() { int a = 10, b = 20, result; result = add(a, b); // Function call printf("Sum: %dn", result); return 0; } Explanation: • The add function is called with arguments a and b. • The result is stored in result and printed. function_name(arguments); • Example:
  • 5. Parameter Passing • Pass by Value: • The value of the actual parameter is copied to the formal parameter. • Changes to the formal parameter do not affect the actual parameter. #include <stdio.h> void increment(int x) { x++; printf("Inside function: %dn", x); } int main() { int a = 10; increment(a); // Pass by value printf("Outside function: %dn", a); return 0; } • Explanation: • The value of a is copied to x. • Changes to x do not affect a.
  • 6. Call by Reference • Pass by Reference: • The address of the actual parameter is passed to the formal parameter. • Changes to the formal parameter affect the actual parameter. • Example: #include <stdio.h> void increment(int *x) { (*x)++; printf("Inside function: %dn", *x); } int main() { int a = 10; increment(&a); // Pass by reference printf("Outside function: %dn", a); return 0; } Explanation: •The address of a is passed to x. •Changes to *x affect a.
  • 7. Passing Arrays to Functions How to Pass Arrays? • Pass the array name (which is a pointer to the first element of the array). • The size of the array is usually passed as an additional parameter. Passing a 1D Array to a Function Syntax: return_type function_name(data_type array[], int size); Call by Reference
  • 8. Passing a 1D Array to a Function example #include <stdio.h> void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("n"); } int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]); printArray(arr, size); // Pass array to function return 0; } Explanation: •The array arr is passed to the function printArray. •The function processes each element of the array.
  • 9. Modifying a 1D Array in a Function example #include <stdio.h> void incrementArray(int arr[], int n) { for (int i = 0; i < n; i++) { arr[i] += 1; // Modify each element of the array } } int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]); incrementArray(arr, size); // Pass array to function printf("Modified Array:n"); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("n"); return 0; } Explanation: • The function incrementArray modifies each element of the array. • Changes are reflected in the original array.
  • 10. Passing a 2D Array to a Function Syntax: return_type function_name(data_type array[][cols], int rows); #include <stdio.h> void printMatrix(int mat[][3], int rows) { for (int i = 0; i < rows; i++) { for (int j = 0; j < 3; j++) { printf("%d ", mat[i][j]); } printf("n"); } } int main() { int mat[2][3] = {{1, 2, 3}, {4, 5, 6}}; printMatrix(mat, 2); // Pass 2D array to function return 0; Explanation: •The 2D array mat is passed to the function printMatrix. •The function processes each element of the 2D array.
  • 11. Passing Arrays to Functions using pointer Why Use Pointers with Arrays? • Pointers provide direct access to memory locations, making array manipulation efficient. • Passing arrays to functions using pointers avoids copying the entire array. •Key Concepts: • Array name is a pointer to the first element of the array. • Pointer arithmetic can be used to traverse arrays.
  • 12. Passing Arrays to Functions using pointer Syntax: return_type function_name(data_type *array, int size); #include <stdio.h> void printArray(int *arr, int n) { for (int i = 0; i < n; i++) { printf("%d ", *(arr + i)); // Access array elements using pointer arithmetic } printf("n"); } int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]); printArray(arr, size); // Pass array using pointer return 0; } Example: Explanation: • The array arr is passed as a pointer to the function printArray. • Pointer arithmetic (*(arr + i)) is used to access array elements.
  • 13. Passing Structures to Functions • How to Pass Structures? Pass by value (a copy of the structure is passed). Pass by reference (a pointer to the structure is passed). • Passing a Structure by Value Syntax : return_type function_name(struct structure_name variable);
  • 14. Passing a Structure by Value example: Passing Structures to Functions #include <stdio.h> struct Student { char name[50]; int rollNo; float marks; }; void printStudent(struct Student s) { printf("Name: %sn", s.name); printf("Roll No: %dn", s.rollNo); printf("Marks: %.2fn", s.marks); } int main() { struct Student student1 = {"John Doe", 101, 95.5}; printStudent(student1); // Pass by value return 0; } Explanation: • A copy of the structure student1 is passed to the function printStudent. • Changes to the structure inside the function do not affect the original structure.
  • 15. Passing Structures to Functions Passing a Structure by Reference Syntax: return_type function_name(struct structure_name *variable);
  • 16. Passing Structures to Functions Passing a Structure by Reference example #include <stdio.h> struct Student { char name[50]; int rollNo; float marks; }; void updateMarks(struct Student *s) { s->marks += 10; // Modify the structure using a pointer } int main() { struct Student student1 = {"John Doe", 101, 95.5}; updateMarks(&student1); // Pass by reference printf("Updated Marks: %.2fn", student1.marks); return 0; } Explanation: • The address of the structure student1 is passed to the function updateMarks. • Changes to the structure inside the function affect the original structure.
  • 17. Passing Structures to Functions Passing an Array of Structures to Functions Why Pass an Array of Structures? • To process multiple records of structured data within a function. • Useful for operations like sorting, searching, or updating. How to Pass an Array of Structures? • Pass the array name (which is a pointer to the first element of the array). Syntax: return_type function_name(struct structure_name array[], int size);
  • 18. Passing an Array of Structures to Functions example: #include <stdio.h> struct Student { char name[50]; int rollNo; float marks; }; void printStudents(struct Student students[], int n) { for (int i = 0; i < n; i++) { printf("Student %d:n", i + 1); printf("Name: %sn", students[i].name); printf("Roll No: %dn", students[i].rollNo); printf("Marks: %.2fn", students[i].marks); } } int main() { struct Student students[3] = { {"Alice", 101, 95.5}, {"Bob", 102, 88.0}, {"Charlie", 103, 92.5} }; printStudents(students, 3); // Pass array of structures return 0; } Explanation: • The array students is passed to the function printStudents. • The function processes each element of the array.
  • 19. Modifying an Array of Structures in a Function example: #include <stdio.h> struct Student { char name[50]; int rollNo; float marks; }; void updateMarks(struct Student students[], int n) { for (int i = 0; i < n; i++) { students[i].marks += 10; // Update marks for each student } } int main() { struct Student students[3] = { {"Alice", 101, 95.5}, {"Bob", 102, 88.0}, {"Charlie", 103, 92.5} }; updateMarks(students, 3); // Pass array of structures printf("Updated Marks:n"); for (int i = 0; i < 3; i++) { printf("Name: %s, Marks: %.2fn", students[i].name, students[i].marks); } return 0; Explanation: • The function updateMarks modifies the marks of each student in the array. • Changes are reflected in the original array.
  • 20. Introduction to Recursion How Recursion Works (Stack Mechanism) Recursion and the Call Stack: Each recursive call creates a new stack frame. The stack grows until the base case is reached. Once the base case is reached, the stack unwinds, and results are returned. Example: Factorial of 3 #include <stdio.h> int factorial(int n) { if (n == 0) return 1; // Base case return n * factorial(n - 1); // Recursive case } int main() { int n = 3; printf("Factorial of %d is %dn", n, factorial(n)); return 0; }
  • 21. Factorial (N!) • N! = (N-1)! * N [for N > 1] • 1! = 1 • 3! = 2! * 3 = (1! * 2) * 3 = 1 * 2 * 3 • Recursive design: • Decomposition: (N-1)! • Composition: * N • Base case: 1!
  • 22. Factorial example #include <stdio.h> int factorial(int n) { if (n == 0) return 1; // Base case return n * factorial(n- 1); // Recursive case } int main() { int n = 5; printf("Factorial of %d is %dn", n, factorial(n)); return 0; }
  • 23. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * factorial(2); // Recursive case }
  • 24. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * factorial(2); // Recursive case } int factorial(int 2) { if (n == 0) return 1; // Base case return 2 * factorial(1); // Recursive case }
  • 25. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * factorial(2); // Recursive case } int factorial(int 2) { if (n == 0) return 1; // Base case return 2 * factorial(1); // Recursive case } int factorial(int 1) { if (n == 0) return 1; // Base case return 1 * factorial(0); // Recursive case }
  • 26. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * factorial(2); // Recursive case } int factorial(int 2) { if (n == 0) return 1; // Base case return 2 * factorial(1); // Recursive case } int factorial(int 1) { if (n == 0) return 1; // Base case return 2 * factorial(1); // Recursive case } int factorial(int 0) { if (n == 0) return 1; // Base case return n * factorial(n - 1); // Recursive case }
  • 27. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * factorial(2); // Recursive case } int factorial(int 2) { if (n == 0) return 1; // Base case return 2 * factorial(1); // Recursive case } int factorial(int 1) { if (n == 0) return 1; // Base case return 1 * factorial(0); // Recursive case } int factorial(int 0) { if (n == 0) return 1; // Base case return n * factorial(n - 1); // Recursive case }
  • 28. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * factorial(2); // Recursive case } int factorial(int 2) { if (n == 0) return 1; // Base case return 2 * factorial(1); // Recursive case } int factorial(int 1) { if (n == 0) return 1; // Base case return 1 * 1; // Recursive case } int factorial(int 0) { if (n == 0) return 1; // Base case return n * factorial(n - 1); // Recursive case }
  • 29. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * factorial(2); // Recursive case } int factorial(int 2) { if (n == 0) return 1; // Base case return 2 * factorial(1); // Recursive case } int factorial(int 1) { if (n == 0) return 1; // Base case return 1; // Recursive case } int factorial(int 0) { if (n == 0) return 1; // Base case return n * factorial(n - 1); // Recursive case }
  • 30. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * factorial(2); // Recursive case } int factorial(int 2) { if (n == 0) return 1; // Base case return 2 * factorial(1); // Recursive case } int factorial(int 1) { if (n == 0) return 1; // Base case return 1; // Recursive case }
  • 31. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * factorial(2); // Recursive case } int factorial(int 2) { if (n == 0) return 1; // Base case return 2 * 1 // Recursive case } int factorial(int 1) { if (n == 0) return 1; // Base case return 1; // Recursive case }
  • 32. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * factorial(2); // Recursive case } int factorial(int 2) { if (n == 0) return 1; // Base case return 2 // Recursive case } int factorial(int 1) { if (n == 0) return 1; // Base case return 1; // Recursive case }
  • 33. int factorial(int 3) { if (n == 0) return 1; // Base case return 3 * 2; // Recursive case } int factorial(int 2) { if (n == 0) return 1; // Base case return 2 // Recursive case }
  • 34. int factorial(int 3) { if (n == 0) return 1; // Base case return 6; // Recursive case }
  • 35. Fibonacci Numbers • The Nth Fibonacci number is the sum of the previous two Fibonacci numbers • 0, 1, 1, 2, 3, 5, 8, 13, … • Recursive Design: • Decomposition & Composition • fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) • Base case: • fibonacci(1) = 0 • fibonacci(2) = 1
  • 36. Fibonacci Numbers #include <stdio.h> int fibonacci(int n) { if (n <= 1) return n; // Base case return fibonacci(n - 1) + fibonacci(n - 2); // Binary recursive call } int main() { int n = 4; printf("Fibonacci number at position %d is %dn", n, fibonacci(n)); return 0; } Fibonacci Sequence Definition The Fibonacci sequence is defined as: • fib(0) = 0 • fib(1) = 1 • fib(n) = fib(n-1) + fib(n-2) for n > 1 For n = 4, the expected Fibonacci number is 3 (since the sequence is: 0, 1, 1, 2, 3).
  • 37. Fibonacci Numbers #include <stdio.h> int fibonacci(int n) { if (n <= 1) return n; // Base case return fibonacci(n - 1) + fibonacci(n - 2); // Binary recursive call } int main() { int n = 4; printf("Fibonacci number at position %d is %dn", n, fibonacci(n)); return 0; } Recursive Execution Tree for fibonacci(4) 1.Initial Call: fibonacci(4) •Since 4 > 1, it calls fibonacci(3) + fibonacci(2). 2.First Subtree: fibonacci(3) •3 > 1 → Calls fibonacci(2) + fibonacci(1). •fibonacci(2) → Calls fibonacci(1) + fibonacci(0). •fibonacci(1) → Returns 1 (base case). •fibonacci(0) → Returns 0 (base case). •Result: 1 + 0 = 1. •fibonacci(1) → Returns 1. •Result: 1 (from fib(2)) + 1 (from fib(1)) = 2. 3.Second Subtree: fibonacci(2) •2 > 1 → Calls fibonacci(1) + fibonacci(0). •fibonacci(1) → Returns 1. •fibonacci(0) → Returns 0. •Result: 1 + 0 = 1. 4.Final Sum: •fibonacci(4) = fibonacci(3) + fibonacci(2) = 2 + 1 = 3.
  • 38. Fibonacci Numbers #include <stdio.h> int fibonacci(int n) { if (n <= 1) return n; // Base case return fibonacci(n - 1) + fibonacci(n - 2); // Binary recursive call } int main() { int n = 4; printf("Fibonacci number at position %d is %dn", n, fibonacci(n)); return 0; } Visualization of Recursive Calls fib(4) = fib(3) + fib(2) = [fib(2) + fib(1)] + [fib(1) + fib(0)] = [ (fib(1) + fib(0)) + 1 ] + [1 + 0] = [ (1 + 0) + 1 ] + 1 = 2 + 1 = 3
  • 39. Types of Recursion • Linear Recursion: • The function makes a single call to itself. • Example: Factorial calculation. • Tail Recursion: • The recursive call is the last operation in the function. • Example: GCD calculation. • Binary Recursion: • The function makes two recursive calls. • Example: Fibonacci sequence. • Mutual Recursion: • Two or more functions call each other. • Example: Determining if a number is even or odd.
  • 40. Stack Overheads in Recursion What are Stack Overheads? • Each recursive call consumes stack space. • Excessive recursion can lead to stack overflow. Example: #include <stdio.h> void recursiveFunction(int n) { if (n == 0) return; printf("Depth: %dn", n); recursiveFunction(n - 1); } int main() { recursiveFunction(5); return 0; } Explanation: • Each call to recursiveFunction adds a new stack frame. • The stack grows with each recursive call.
  • 41. Key Points to Remember 1. Functions provide modularity and reusability. 2. Parameters can be passed by value or by reference. 3. Recursion is a powerful technique but can lead to stack overheads. 4. Tail recursion can be optimized by the compiler.
  • 42. Exercises 1. Write a recursive function to calculate the sum of digits of a number. 2. Write a program to GCD Calculation Using Recursion 3. Write a recursive function to calculate the power of a number. 4. Write two mutually recursive functions to determine if a number is a multiple of 3 or 5
  • 44. #include <stdio.h> int sumOfDigits(int n) { if (n == 0) return 0; // Base case return (n % 10) + sumOfDigits(n / 10); // Linear recursive call } int main() { int n = 12345; printf("Sum of digits of %d is %dn", n, sumOfDigits(n)); return 0; } Sum of Digits
  • 45. #include <stdio.h> int gcd(int a, int b) { if (b == 0) return a; // Base case return gcd(b, a % b); // Recursive call } int main() { int a = 56, b = 98; printf("GCD of %d and %d is %dn", a, b, gcd(a, b)); return 0; } Recursive Function for GCD Step-by-Step Execution • Input: a = 56, b = 98 • Step 1: gcd(56, 98) • b ≠ 0, so call gcd(98, 56 % 98) → gcd(98, 56) • Step 2: gcd(98, 56) • b ≠ 0, so call gcd(56, 98 % 56) → gcd(56, 42) • Step 3: gcd(56, 42) • b ≠ 0, so call gcd(42, 56 % 42) → gcd(42, 14) • Step 4: gcd(42, 14) • b ≠ 0, so call gcd(14, 42 % 14) → gcd(14, 0) • Step 5: gcd(14, 0) • b == 0, so return 14 (base case). • Final Result: 14
  • 46. #include <stdio.h> int power(int x, int n) { if (n == 0) return 1; // Base case return x * power(x, n - 1); // Binary recursive call } int main() { int x = 2, n = 5; printf("%d^%d is %dn", x, n, power(x, n)); return 0; } Power Calculation
  • 47. #include <stdio.h> int isMultipleOf3(int n); int isMultipleOf5(int n); int isMultipleOf3(int n) { if (n == 0) return 1; // Base case if (n < 0) return 0; return isMultipleOf5(n - 3); // Mutual recursive call } int isMultipleOf5(int n) { if (n == 0) return 1; // Base case if (n < 0) return 0; return isMultipleOf3(n - 5); // Mutual recursive call } int main() { int n = 15; if (isMultipleOf3(n)) { printf("%d is a multiple of 3n", n); } else if (isMultipleOf5(n)) { printf("%d is a multiple of 5n", n); } else { printf("%d is not a multiple of 3 or 5n", n); } return 0; } Multiple of 3 or 5

Editor's Notes

  • #4: Output: Sum: 30
  • #5: Output: Inside function: 11 Outside function: 10
  • #6: Output: Inside function: 11 Outside function: 11
  • #8: Output: 1 2 3 4 5
  • #9: Output: Modified Array: 2 3 4 5 6
  • #10: Output: 1 2 3 4 5 6
  • #12: Output: 1 2 3 4 5
  • #14: Output: Name: John Doe Roll No: 101 Marks: 95.50
  • #16: Output: Updated Marks: 105.50
  • #18: Output: Student 1: Name: Alice Roll No: 101 Marks: 95.50 Student 2: Name: Bob Roll No: 102 Marks: 88.00 Student 3: Name: Charlie Roll No: 103 Marks: 92.50
  • #19: Output: Updated Marks: Name: Alice, Marks: 105.50 Name: Bob, Marks: 98.00 Name: Charlie, Marks: 102.50
  • #20: Output: Factorial of 5 is 120
  • #39: The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both of them without leaving a remainder. Example: GCD of 56 and 98 is 14. Recursive Function for GCD #include <stdio.h> int gcd(int a, int b) { if (b == 0) return a; // Base case return gcd(b, a % b); // Recursive call } int main() { int a = 56, b = 98; printf("GCD of %d and %d is %d\n", a, b, gcd(a, b)); return 0; }
  • #40: Output: Depth: 5 Depth: 4 Depth: 3 Depth: 2 Depth: 1
  • #45: GCD of 56 and 98 is 14
  翻译: