Lecture_Week_9.2
Lecture_Week_9.2
Programming
Recursion
Recap
5. Write a function to check whether a number can be expressed as the sum of two
prime numbers
You may use a separate method to check primality
#include <stdio.h>
void reverseArray(char arr[], int k) {
int start = 0;
Reversal operation
int end = k - 1;
// Reverse the characters in the array int main() {
char arr[] = "Hello Class!";
while (start < end) {
int size = sizeof(arr)/sizeof(arr[0]);
// Swap the characters printf("%d\n",size);
char temp = arr[start]; reversestring(arr,size);
arr[start] = arr[end];
for (int i = 0; i < size; i++) {
arr[end] = temp;
printf("%c", arr[i]);
start++; }
end--; return 0;
} }
}
Count the number of Vowels, Consonants else if (line[i] >= '0' && line[i] <= '9') {
and symbols and print the same ++digit;
}
#include <stdio.h> else if (line[i] == ' ') {++space; }
void countfunction(char line[], int size) else{++others;}
}
{int vowels, consonant, digit, space,others;
printf("Vowels: %d", vowels);
vowels = consonant = digit = space = others = 0; printf("\nConsonants: %d", consonant);
for (int i = 0; i < size; ++i) { printf("\nDigits: %d", digit);
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' || printf("\nWhite spaces: %d", space);
printf("\nOthers: %d", others);
line[i] == 'o' || line[i] == 'u' || line[i] == 'A' ||
}
line[i] == 'E' || line[i] == 'I' || line[i] == 'O' || line[i]
== 'U') { int main() {
char line[] = "Hello, how are you?";
++vowels; } int size = sizeof(line)/sizeof(line[0]);
else if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= countfunction(line, size);
'A' && line[i] <= 'Z')) { return 0;
++consonant;} }
Content
• What is Recursion?
• How Recursion works?
• Types of Recursion
• Advantages & Disadvantages of Recursion
Recursion
What is Recursion?
// Iteratively multiply result by i (from 2 to n) printf("Factorial is not defined for negative numbers.\n");
for (int i = 2; i <= n; i++) { } else {
result *= i; // Call the function and print the result
} int factorial = calculateFactorial(number);
return result; // Return the factorial result printf("Factorial of %d is: %d\n", number, factorial);
}
}
int main() {
int number;
// Ask the user for input return 0;
printf("Enter a number to calculate its factorial: "); }
scanf("%d", &number);
How to solve using Recursion?
int main(void) {
CountDown(2);
return 0;
}
Write a C program to calculate the sum of n
number using Recursion
Eg: enter the number 5
5+4+3+2+1=15
Write a C program to calculate the sum of n
number using Recursion
#include <stdio.h>
int main()
int nSum(int n)
{
{
int n = 5;
// base condition to terminate the recursion
when N = 0
if (n == 0) { // calling the function
return 0; int sum = nSum(n);
} printf("Sum of First %d Natural
Numbers: %d", n, sum);
// recursive case / recursive call
return 0;
int res = n + nSum(n - 1);
}
return res;}
Recursion
Tree Diagram
of nSum(5)
Function
Function call Stack
of nSum(5)
Function Returning
Value
Types of Recursion