0% found this document useful (0 votes)
8 views

3 Recursion

Uploaded by

karanjaiswalf39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

3 Recursion

Uploaded by

karanjaiswalf39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Assignment no.

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()

int arr[] = {1,2,3,4,5,6}; int n =

sizeof(arr)/sizeof(arr[O]); int

res = ArraySum(arr,n);

prin ("Sum = ,res);

OUTPUT

Sum = -802206203

Code Execu on Successful

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];

prin ("Enter your string:

"); fgets(str, sizeof(str),

stdin); str[strcspn(str,

"\n")] = '\O'; reverse(str);

OUTPUT

Enter your string: Himanshu uhsnamiH

Code Execu on Successful

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

palindrome(char c[100],int i, int j)

if (j i)

return 1;

c[j])

return palindrome(c, ++i,


} else {

return O;

return O;

int main(void)

char str[100]; prin ("Enter your

string: "); fgets(str,sizeof(str),stdin);

str[strcspn(str, "\n" int pal; pal

= palindrome(str, O, (strlen(str)-l));

if(pal==l)

prin ("Given string is a palindrome");

else{ prin ("Given string is not a

palindrome");

return O;

OUTPUT

Enter your string: Tanishka

Given string is not a palindrome

Code Execu on Successful

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

power(int n,int pow)

if(pow>O)

return n*power(n,(pow-l));

else if(pow<O)

return l/(power(n,(-pow)));

return 1;

int main()

int n,pow; prin ("Enter

number: ");

prin ("Enter power: ");

,&pow); float

res = power(n,pow);

prin ("Result =

%f",res);

OUTPUT

Enter number: 2
Enter power: 6

Result = 64.000000

Code Execu on Successful

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)

prin ("\n%c %c",S,D);

%c",S,D);

int main()

int n; prin ("Enter number of


Discs: "),

OUTPUT
Enter number of Discs: 3

Code Execu on Successful

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

swap(char *x, char *y) {

char temp; temp = *x;

*y = temp;

// Recursive func on to generate


permuta ons void permute(char *str, int l, int
r) { if (l r) {
prin ("%s\n", str);

} else { for (int i swap((str + l), (str + i)); // Swap the


characters permute(str, I + 1, r); // Recursively permute the
remaining string swap((str + l), (str + i)); // Backtrack by swapping
the characters back

int main()

char str[10]; prin ("Enter

your string: "); fgets(str,

sizeof(str), stdin);

str[strcspn(str, "\n")] =

'\O'; int n = strlen(str);

permute(str,O,n-1);

OUTPUT

Enter your string: abc

abc acb bac bca cba

cab

Code Execu on Successful


Part 2
1. Calculate the Length: Create a recursive func on to find the length (number of nodes) of a linked list. The func on
should count the number of nodes by recursively calling itself with the next node un l it reaches the end.

#include <stdio.h>

#include <stdlib.h>

// Define the structure for a linked list

node struct Node { int data; struct Node*

next;

// Recursive func on to calculate the length of the linked list


int calculateLength(struct Node* head) {
// Base case: if the head is NULL, the length is
O if (head NULL) {
return O;

// Recursive case: 1 (for the current node) + length of the rest of the list
return 1 + calculateLength(head->next);

// U lity func on to create a new node struct Node* createNode(int

data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct

Node)); newNode->data = data; newNode->next = NULL; return

newNode;

// Main func on to test the calculateLength func on


int main() {
// Crea ng a simple linked list: 1 2 3 4

struct Node* head = createNode(1); head-

>next = createNode(2); head->next->next =

createNode(3); head->next->next->next =

createNode(4); // Calculate the length of

the linked list int length =

calculateLength(head);

// Print the length of the linked list

prin ("Length of the linked list is: length);

return O;
OUTPUT

Length of the linked list is: 4

Code Execu on Successful

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>

// Define the structure for a linked list

node struct Node { int data; struct Node*

next;

// Recursive func on to search for a specific value in the linked list


int searchElement(struct Node* head, int target) {
// Base case: if the head is NULL, the element is not

found if (head NULL) { return O; // O indicates the target

is not found

// If the current node's data matches the target, return 1


if (head->data target) { return 1; // 1

indicates the target is found

// Otherwise, search in the rest of the list

return searchElement(head->next, target);

// U lity func on to create a new node struct Node*

createNode(int data) { struct Node* newNode = (struct

Node*)malloc(sizeof(struct Node)); newNode->data = data;

newNode->next = NULL; return newNode;

// Main func on to test the searchElement func on


int main() {

// Crea ng a simple linked list: 1 2 3 4 struct Node* head

= createNode(1); head->next = createNode(2); head-

>next->next = createNode(3); head->next->next->next =

createNode(4); // Search for an element in the linked list

int target = 3; if (searchElement(head, target)) {

prin ("Element %d is found in the linked list.\n", target);

} else {
prin ("Element %d is not found in the linked list.\n", target);

return O;

OUTPUT

Element 3 is found in the linked list.

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>

Code Execu on Successful


// Define the structure for a linked list

node struct Node { int data; struct Node*

next;

// Recursive func on to merge two sorted linked lists struct Node*


mergeSortedLists(struct Node* listl, struct Node* list2) {
// Base cases if
(listl NULL) {
return list2;

if (list2 NULL) { return


listl;

// Recursive case: compare the data of the two


lists if (listl->data list2->data) { listl->next =
mergeSortedLists(list1->next, list2); return listl;
} else { list2->next = mergeSortedLists(list1, list2-

>next); return list2;

// U lity func on to create a new node struct Node*

createNode(int data) { struct Node* newNode = (struct

Node*)malloc(sizeof(struct Node)); newNode->data = data;

newNode->next = NULL; return newNode;

// U lity func on to print the linked list

void printList(struct Node* head) {


struct Node* temp = head;

while (temp NULL) {


prin ("%d ", temp->data);
temp = temp->next;

// Main func on to test the mergeSortedLists func on

int main() {

// Crea ng first sorted linked list: 1 3 5


struct Node* listl = createNode(1);
listl->next = createNode(3);

listl->next->next = createNode(5);

// Crea ng second sorted linked list: 2 4 6

struct Node* list2 = createNode(2);

list2->next = createNode(4);

list2->next->next = createNode(6);

// Merge the two sorted linked lists

struct Node* mergedList = mergeSortedLists(list1, list2);

// Print the merged linked list

prin ("Merged Sorted Linked List:\n");

printList(mergedList);

return O;

OUTPUT

Merged Sorted Linked List:

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>

// Define the structure for a linked list

node struct Node { int data; struct Node*

next;

// Recursive func on to reverse the linked list


struct Node* reverseList(struct Node* head) {
// Base case: if the list is empty or has only one node, return the
head if (head NULL I I head->next NULL) { return head;

Code Execu on Successful


// Recursively reverse the rest of the list struct

Node* newHead = reverseList(head->next); //

Adjust the next pointer of the current node

head->next->next = head; head->next = NULL;

return newHead;

// U lity func on to create a new node struct Node*

createNode(int data) { struct Node* newNode = (struct

Node*)malloc(sizeof(struct Node)); newNode->data = data;

newNode->next = NULL; return newNode;

// U lity func on to print the linked


list void printList(struct Node* head) {
struct Node* temp = head; while
(temp NULL) {
prin ("%d ", temp->data); temp

= temp->next;

// Main func on to test the reverseList func on


int main() {

// Crea ng a simple linked list: 1 2 3 4 struct

Node* head = createNode(1); head->next =

createNode(2); head->next->next =

createNode(3); head->next->next->next =

createNode(4); // Print the original linked

list prin ("Original Linked List:\n");

printList(head); // Reverse the linked list

head = reverseList(head); // Print the

reversed linked list prin ("Reversed Linked

List:\n"); printList(head);

return O;
OUTPUT
Original Linked List:

1 2 3 4 NULL Reversed
Linked List: 4 3 2 -> 1
NULL

Code Execu on Successful


5. Find the Middle Node: Write a recursive func on 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 me and the other moving two steps at a me.

#include <stdio.h>

#include <stdlib.h>

// Define the structure for a linked list

node struct Node { int data; struct Node*

next;

// Helper func on to find the middle node struct Node*


findMiddleHelper(struct Node* slow, struct Node* fast) { // Base
case: when fast or fast->next is NULL, slow is at the middle if (fast
NULL I I fast->next NULL) { return slow;

// Move slow by one step and fast by two steps

return findMiddleHelper(slow->next, fast->next-

>next);

// Func on to find the middle node using the


helper struct Node* findMiddle(struct Node*
head) { if (head NULL) { return NULL; // If the list is
empty, return NULL

return findMiddleHelper(head, head);

// U lity func on to create a new node struct Node* createNode(int

data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct

Node)); newNode->data = data; newNode->next = NULL; newNode;

// U lity func on to print the linked

list void printList(struct Node* head)

{ struct Node* temp = head; while

(temp NULL) { prin ("%d ", temp-

>data); temp = temp->next;

return
// Main func on to test the findMiddle func on
int main() {

// Crea ng a simple linked list: 1 2 3 4 5 struct

Node* head = createNode(1); head->next =

createNode(2); head->next->next =

createNode(3); head->next->next->next =

createNode(4); head->next->next->next->next

= createNode(5);

// Print the original linked list

prin ("Original Linked

List:\n"); printList(head);

// Find the middle node struct Node*

middle = findMiddle(head);

// Print the middle node if (middle NULL) {

prin ("Middle Node: middle->data);

} else {
prin ("The linked list is empty.\n");

O;

OUTPUT

Original Linked List: 1 2 3-


>4 5 NULL
Middle Node: 3

Code Execu on Successful

6. Parentheses Balancing: Implement two mutually recursive func ons named


"isOpenParenthesis" and "isBalanced" to check whether a given string of parentheses is balanced.

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>

// Func on prototypes int isBalanced(const

char* str, int* index); int

isOpenParenthesis(const char* str, int* index);

// Func on to check if the current character is an opening


parenthesis int isOpenParenthesis(const char* str, int* index) { if
(str[*index] {
// Move to the next character

if (isBalanced(str, index)) { // Check the substring within the


parentheses if (str[*index] { // Ensure there is a closing
parenthesis
// Move past the closing parenthesis

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;

// Main func on to check if the parentheses in a string are

balanced int main() { char str[100]; prin ("Enter a string

containing parentheses: "), scanf("%s", str); int index = O; if

(isBalanced(str, &index) && str[index] prin ("The

parentheses are balanced.\n");

} else {
prin ("The parentheses are not balanced.\n");

return O;

OUTPUT

Enter a string containing parentheses: {(a+b)


The parentheses are not balanced.

Code Execu on Successful

You might also like