3 Recursion
3 Recursion
3
Title: Use of Recursion
Pan 1 and Part 2 are mandatory.
Pan 3 is bonus. You can expect part 3 type questions in the end semester exam.
Lab copy (handwritten part: additional content must include the following): Indicate the decomposition, composition
and base case(s) for all the problems in part 1.
• Part 1
1. Array Sum: a) Implement a recursive fimction named "an•aySum" that calculates the sum of elements
in an integer may. b) Create an integer an•ay with a few elements, and then call the "an•aySum"
fimction to calculate and display the sum.
2. String Reversal: a) Implement a recmsive fimction named "reverseString" that reverses a given string.
b) Prompt the user to input a string, and then call the "reverseString" fimction to display the reversed
string.
3. Palindrome Check: Write a recursive fimction to determine if a given string is a palindrome. A
palindrome is a word, phrase, number, or other sequence of characters that reads the same forward
and backward (ignoring spaces, punctuation, and capitalization).
4. Power Function: Create a recursive mnction to calculate the value of base raised to the power of
exponent, where both base and exponent are positive integers. Make sure it handles all the boundary
cases.
5. Tower of Hanoi: Solve the classic Tower of Hanoi problem using recursion. Given three pegs and a
stack of n disks of different sizes, move the entire stack from one peg to another with the following
rules: Only one disk can be moved at a time, and a larger disk cannot be placed on top of a smaller
disk.
6. Permutations: Implement a recursive fimction to generate all possible permutations of a given string.
A permutation of a string is an arrangement of its characters in a different order.
• Part 2
1. Calculate the Length: Create a recursive mnction to find the length (number of nodes) of a linked list.
The fimction should count the number of nodes by recursively calling itself with the next node until it
reaches the end.
2. Search for an Element: Implement a recursive fimction to search for a specific value in the linked list.
The mnction should traverse the list by calling itself with the next node until it finds the target value
or reaches the end.
3. Merge Two Sorted Lists: Write a recursive mnction to merge two sorted linked lists into a single sorted
linked list. The function should compare the values of the nodes in both lists and recursively merge
them to create a new sorted list.
4. Reverse the Linked List: Implement a recursive fimction to reverse the linked list. The fimction should
recursively reverse the rest of the list and adjust the next pointers as it traverses back.
5. Find the Middle Node: Write a recursive fimction to find the middle node of a linked list. The middle
node is the one located at approximately the center of the list. You can use two pointers to traverse the
list—one moving one step at a time and the other moving two steps at a time.
6. Parentheses Balancing: Implement two mutually recursive fimctions named
"isOpenParenthesis" and "isBalanced" to check whether a given string of parentheses is balanced.
a. The "isOpenParenthesis" mnction should call "isBalanced" to check the substring within the
parentheses.
b. The "isBalanced" fimction should call "isOpenParenthesis" to check if the opening
parenthesis has a matching closing parenthesis.
c. Prompt the user to input a string containing parentheses, and then call the "isBalanced"
mnction to determine and display whether the parentheses are balanced.
Part 1
1. Array Sum: a) Implement a recursive func on named "arraySum" that calculates the sum of elements in an integer
array. b) Create an integer array with a few elements, and then call the "arraySum" func on to calculate and display
the sum.
#include<stdio.h>
#include<stdbool.h> int
ArraySum(int arr[],int n)
while(n>=l)
return arr[n-1]+ArraySum(arr,n-1);
int main()
sizeof(arr)/sizeof(arr[O]); int
res = ArraySum(arr,n);
OUTPUT
Sum = -802206203
2. String Reversal: a) Implement a recursive func on named "reverseString" that reverses a given string. b) Prompt the
user to input a string, and then call the "reverseString" func on to display the reversed string.
#include<stdio.h>
#include<stdbool.h>
#include<string.h>
void reverse(char
*str)
if (*str)
reverse(str+l);
*str);
int main()
char str[100];
stdin); str[strcspn(str,
OUTPUT
3. Palindrome Check: Write a recursive func on to determine if a given string is a palindrome. A palindrome is a
word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces,
punctua on, and capitaliza on).
#include<stdio.h>
#include<stdbool.h>
#include<string.h> int
if (j i)
return 1;
c[j])
return O;
return O;
int main(void)
= palindrome(str, O, (strlen(str)-l));
if(pal==l)
palindrome");
return O;
OUTPUT
4. Power Func on: Create a recursive func on to calculate the value of base raised to the power of exponent, where
both base and exponent are posi ve integers. Make sure it handles all the boundary cases.
#include<stdio.h>
#include<stdbool.h>
#include<string.h> float
if(pow>O)
return n*power(n,(pow-l));
else if(pow<O)
return l/(power(n,(-pow)));
return 1;
int main()
number: ");
,&pow); float
res = power(n,pow);
prin ("Result =
%f",res);
OUTPUT
Enter number: 2
Enter power: 6
Result = 64.000000
5. Tower of Hanoi: Solve the classic Tower of Hanoi problem using recursion. Given three pegs and a stack of n disks of
different sizes, move the en re stack from one peg to another with the following rules: Only one disk can be moved
at a me, and a larger disk cannot be placed on top of a smaller disk.
#include<stdio.h>
#include<stdbool.h> void ToH(int
n,char S, char A, char D)
if(n==l)
%c",S,D);
int main()
OUTPUT
Enter number of Discs: 3
6. Permuta ons: Implement a recursive func on to generate all possible permuta ons of a given string. A permuta on
of a string is an arrangement of its characters in a different order.
#include<stdio.h>
#include<stdbool.h>
#include<string.h> void
*y = temp;
int main()
sizeof(str), stdin);
str[strcspn(str, "\n")] =
permute(str,O,n-1);
OUTPUT
cab
#include <stdio.h>
#include <stdlib.h>
next;
// Recursive case: 1 (for the current node) + length of the rest of the list
return 1 + calculateLength(head->next);
newNode;
createNode(3); head->next->next->next =
calculateLength(head);
return O;
OUTPUT
2. Search for an Element: Implement a recursive func on to search for a specific value in the linked list. The func on
should traverse the list by calling itself with the next node un l it finds the target value or reaches the end.
#include <stdio.h>
#include <stdlib.h>
next;
is not found
} else {
prin ("Element %d is not found in the linked list.\n", target);
return O;
OUTPUT
3. Merge Two Sorted Lists: Write a recursive func on to merge two sorted linked lists into a single sorted linked list.
The func on should compare the values of the nodes in both lists and recursively merge them to create a new
sorted list.
#include <stdio.h>
#include <stdlib.h>
next;
int main() {
listl->next->next = createNode(5);
list2->next = createNode(4);
list2->next->next = createNode(6);
printList(mergedList);
return O;
OUTPUT
1 2 3 4 5 6 NULL
4. Reverse the Linked List: Implement a recursive func on to reverse the linked list. The func on should
recursively reverse the rest of the list and adjust the next pointers as it traverses back.
#include <stdio.h>
#include <stdlib.h>
next;
return newHead;
= temp->next;
createNode(2); head->next->next =
createNode(3); head->next->next->next =
List:\n"); printList(head);
return O;
OUTPUT
Original Linked List:
1 2 3 4 NULL Reversed
Linked List: 4 3 2 -> 1
NULL
#include <stdio.h>
#include <stdlib.h>
next;
>next);
return
// Main func on to test the findMiddle func on
int main() {
createNode(2); head->next->next =
createNode(3); head->next->next->next =
createNode(4); head->next->next->next->next
= createNode(5);
List:\n"); printList(head);
middle = findMiddle(head);
} else {
prin ("The linked list is empty.\n");
O;
OUTPUT
a. The "isOpenParenthesis" func on should call "isBalanced" to check the substring within the parentheses.
return
b. The "isBalanced" func on should call "isOpenParenthesis" to check if the opening parenthesis has a
matching closing parenthesis.
c. Prompt the user to input a string containing parentheses, and then call the "isBalanced" func on to
determine and display whether the parentheses are balanced.
#include <stdio.h>
#include <string.h>
1;
return
return O;
// Func on to check if the string is balanced int isBalanced(const char* str, int*
index) { while (str[*index] '\O' && str[*index] { if (!isOpenParenthesis(str,
index)) { // Check if there is an opening parenthesis return O;
return 1;
} else {
prin ("The parentheses are not balanced.\n");
return O;
OUTPUT