New Chat
New Chat
Assignment
Recursion:
1) Write a recursive function to calculate the sum of digits of a given number.
Input: 1234
Output: 10
2) Write a recursive function to reverse a given string.
Input: "hello"
Output: "olleh"
3) Write a recursive function to find the nth number in the Fibonacci series.
Input: 6
Output: 8
4) Write a recursive function to find the GCD (Greatest Common Divisor) of two numbers
using the Euclidean algorithm.
Input: 48, 18
Output: 6
5) Write a recursive function to check if a given number is a palindrome (reads the same
forward and backward).
Input: 121
Output: 1
Sorting:
1) Write a C program that sorts an array of integers in descending order using the
Bubble Sort algorithm with recursion. Additionally, optimize the algorithm to stop
early if the array becomes sorted before completing all passes.
Input:
6
8 2 6 4 10 3
Output:
Original array: 8 2 6 4 10 3
Sorted array in descending order: 10 8 6 4 3 2
in C each seperately
Recursion Programs:
#include <stdio.h>
int sumOfDigits(int n) {
if (n == 0)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/4
return 0;
return (n % 10) + sumOfDigits(n / 10);
}
int main() {
int num = 1234;
printf("Sum of digits: %d\n", sumOfDigits(num));
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello";
int len = strlen(str);
reverseString(str, 0, len - 1);
printf("Reversed string: %s\n", str);
return 0;
}
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n = 6;
printf("Fibonacci number at position %d: %d\n", n, fibonacci(n));
return 0;
}
#include <stdio.h>
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/4
return gcd(b, a % b);
}
int main() {
int num1 = 48, num2 = 18;
printf("GCD of %d and %d: %d\n", num1, num2, gcd(num1, num2));
return 0;
}
#include <stdio.h>
int main() {
int num = 121;
printf("Is palindrome: %d\n", isPalindrome(num));
return 0;
}
Sorting Program:
#include <stdio.h>
swapped = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] < arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = 1;
}
}
bubbleSort(arr, n - 1, swapped);
}
int main() {
int arr[] = {8, 2, 6, 4, 10, 3};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n, 1);
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/4
printf("Sorted array in descending order: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
These programs are simple, efficient, and correctly implement recursion and sorting as per your
assignment. Let me know if you need any modifications! 🚀
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/4