Write a recursive function named isPalindrome(), which receives a string and checks if a given string is a palindrome (reads the same forwards and backwards).
The function should take the string and relevant indices (start and end) as arguments and return 1 (true) or 0 (false).
In main(), you need to input a word from the user and pass it to the function, then display “Yes” if it is a palindrome and “No” otherwise.
Example:
Enter a word: racecar
Result: The word is a Palindrome
Example 2:
Enter a word: hello
Result: The word is not a Palindrome
Solution
#include<stdio.h>intisPalindrome(charstr[],intstart,intend){if(start>=end){return1;}if(str[start]!=str[end]){return0;}returnisPalindrome(str,start+1,end-1);}intmain(){charword[100];printf("Enter the word: ");scanf("%s",word);intlength,i=0;while(word[i]!='\0'){i++;}length=i;// Updated output to match worksheet exampleif(isPalindrome(word,0,length-1)){printf("Result: Yes\n");}else{printf("Result: No\n");}return0;}
#include<iostream>
#include<string>usingnamespacestd;intisPalindrome(conststring&str,intstart,intend){if(start>=end)return1;if(str[start]!=str[end])return0;returnisPalindrome(str,start+1,end-1);}intmain(){stringword;cout<<"Enter the word: ";cin>>word;if(isPalindrome(word,0,word.length()-1)){cout<<"Result: Yes\n";}else{cout<<"Result: No\n";}return0;}
Exercise 2: Sum of Digits
Write a recursive function named sumDigits(), that receives an integer num argument and recursively calculates the sum of its digits.
In main(), you need to ask the user for a non-negative integer, pass it to the function, and print the result.
Example:
Enter a number: 1234
Sum of digits: 10
(Calculation: \(1+2+3+4 = 10\))
Solution
#include<stdio.h>intsumDigits(intn){if(n==0){return0;}return(n%10)+sumDigits(n/10);}intmain(){intnum;printf("Enter a number: ");scanf("%d",&num);printf("Sum of digits: %d\n",sumDigits(num));return0;}
#include<iostream>usingnamespacestd;intsumDigits(intn){if(n==0)return0;return(n%10)+sumDigits(n/10);}intmain(){intnum;cout<<"Enter a number: ";cin>>num;cout<<"Sum of digits: "<<sumDigits(num)<<"\n";return0;}
Exercise 3: Lake Volume Simulator
Assume we have a lake that changes in volume according to the daily weather conditions:
Sunny (35% probability): Loses 2% of volume.
Rainy (30% probability): Increases by 1% of volume.
Cloudy (35% probability): Volume stays the same.
Write a recursive function computeVolume(float V, int N) that takes the current volume V and number of days N, and returns the resulting volume after simulating N days.
In main(), input the initial volume and number of days from the user.
Example:
Enter initial volume: 1000
Enter number of days: 3
Day 1: Sunny (Vol: 980.00)
Day 2: Cloudy (Vol: 980.00)
Day 3: Rainy (Vol: 989.80)
Final Volume: 989.80
Note: Since weather is random, your output will vary.
Solution
#include<stdio.h>
#include<stdlib.h>
#include<time.h>floatcomputeVolume(floatV,intN){if(N==0){returnV;}floatprevVol=computeVolume(V,N-1);intprob=rand()%100;floatcurrentVol=prevVol;if(prob<30){currentVol=prevVol*1.01;printf("Day %d: Rainy (Vol: %.2f)\n",N,currentVol);}elseif(prob<65){currentVol=prevVol*0.98;printf("Day %d: Sunny (Vol: %.2f)\n",N,currentVol);}else{printf("Day %d: Cloudy (Vol: %.2f)\n",N,currentVol);}returncurrentVol;}intmain(){srand(time(0));floatstartVolume;intdays;printf("Enter initial volume and number of days: ");scanf("%f %d",&startVolume,&days);floatfinalVol=computeVolume(startVolume,days);printf("Final Volume: %.2f\n",finalVol);return0;}
#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<ctime>usingnamespacestd;floatcomputeVolume(floatV,intN){if(N==0)returnV;floatprevVol=computeVolume(V,N-1);intprob=rand()%100;floatcurrentVol=prevVol;if(prob<30){currentVol=prevVol*1.01;cout<<"Day "<<N<<": Rainy (Vol: "<<fixed<<setprecision(2)<<currentVol<<")\n";}elseif(prob<65){currentVol=prevVol*0.98;cout<<"Day "<<N<<": Sunny (Vol: "<<fixed<<setprecision(2)<<currentVol<<")\n";}else{cout<<"Day "<<N<<": Cloudy (Vol: "<<fixed<<setprecision(2)<<currentVol<<")\n";}returncurrentVol;}intmain(){srand(time(0));floatstartVolume;intdays;cout<<"Enter initial volume and number of days: ";cin>>startVolume>>days;floatfinalVol=computeVolume(startVolume,days);cout<<"Final Volume: "<<fixed<<setprecision(2)<<finalVol<<"\n";return0;}
Exercise 4: Reverse String
Develop a recursive function named reverseString() that takes a String s and prints it in reverse.
Notice that the first character of the reverse is the last character of the original string.
In main(), you need to input a string from the user and call the function to display the reversed version.
Example:
Enter a string: structure
Reversed: erutcurts
Solution
#include<stdio.h>voidprintReverse(charstr[],intn){if(n==0){return;}printf("%c",str[n-1]);printReverse(str,n-1);}intmain(){charword[100];printf("Enter the string: ");scanf("%s",word);intlength,i=0;while(word[i]!='\0'){i++;}length=i;printf("Reversed: ");printReverse(word,length);printf("\n");return0;}
#include<iostream>
#include<string>usingnamespacestd;voidprintReverse(conststring&str,intn){if(n==0)return;cout<<str[n-1];printReverse(str,n-1);}intmain(){stringword;cout<<"Enter the string: ";cin>>word;cout<<"Reversed: ";printReverse(word,word.length());cout<<"\n";return0;}
Exercise 5: Max Element in Array
Write a recursive function named findMax() that finds the maximum number in an array of integers.
In main(), define an array (e.g., [10, 5, 20, 8]) or ask the user to fill one, and print the maximum value found by your function.
Example:
Enter number of elements: 4
Enter elements: 10 5 20 8
Max number is: 20
Solution
#include<stdio.h>intfindMax(intarr[],intn){if(n==1){returnarr[0];}intmx=findMax(arr,n-1);if(arr[n-1]>mx){returnarr[n-1];}else{returnmx;}}intmain(){intn;printf("Enter number of elements: ");scanf("%d",&n);intarr[n];printf("Enter elements: ");for(inti=0;i<n;i++){scanf("%d",&arr[i]);}printf("Max number is: %d\n",findMax(arr,n));return0;}
#include<iostream>usingnamespacestd;intfindMax(intarr[],intn){if(n==1)returnarr[0];intmx=findMax(arr,n-1);return(arr[n-1]>mx)?arr[n-1]:mx;}intmain(){intn;cout<<"Enter number of elements: ";cin>>n;intarr[n];cout<<"Enter elements: ";for(inti=0;i<n;i++)cin>>arr[i];cout<<"Max number is: "<<findMax(arr,n)<<"\n";return0;}
Exercise 6: Find the Output
Consider the following recursive function. What will be the output if fun(3) is called?
Consider an algorithm that takes as input a positive integer n. If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until n is one. For example, the sequence for n=3 is as follows:
Write a function that counts how many times a specific digit appears in a number (e.g., counting how many 7s are in 7071 should return 2).
Solution
#include<stdio.h>intcountDigits(intnum,inttarget){if(num==0)return0;intlastDigit=num%10;if(lastDigit==target)return1+countDigits(num/10,target);elsereturncountDigits(num/10,target);}intmain(){intnum,target;printf("Enter a number: ");scanf("%d",&num);printf("Enter digit to count: ");scanf("%d",&target);printf("Count: %d\n",countDigits(num,target));return0;}
#include<iostream>usingnamespacestd;intcountDigits(intnum,inttarget){if(num==0)return0;intlastDigit=num%10;if(lastDigit==target)return1+countDigits(num/10,target);elsereturncountDigits(num/10,target);}intmain(){intnum,target;cout<<"Enter a number: ";cin>>num;cout<<"Enter digit to count: ";cin>>target;cout<<"Count: "<<countDigits(num,target)<<endl;return0;}
Exercise 11: Count Occurrences of an Item
Write a function that takes an array and a target value, and returns how many times that target value appears in the array.
Solution
#include<stdio.h>intcountOccurrences(intarr[],intsize,inttarget){if(size==0)return0;if(arr[size-1]==target)return1+countOccurrences(arr,size-1,target);elsereturncountOccurrences(arr,size-1,target);}intmain(){intsize;printf("Enter number of elements: ");scanf("%d",&size);intarr[size];printf("Enter elements: ");for(inti=0;i<size;i++){scanf("%d",&arr[i]);}inttarget;printf("Enter target: ");scanf("%d",&target);printf("Count: %d\n",countOccurrences(arr,size,target));return0;}
#include<iostream>usingnamespacestd;intcountOccurrences(intarr[],intsize,inttarget){if(size==0)return0;if(arr[size-1]==target)return1+countOccurrences(arr,size-1,target);elsereturncountOccurrences(arr,size-1,target);}intmain(){intsize;cout<<"Enter number of elements: ";cin>>size;intarr[size];cout<<"Enter elements: ";for(inti=0;i<size;i++){cin>>arr[i];}inttarget;cout<<"Enter target: ";cin>>target;cout<<"Count: "<<countOccurrences(arr,size,target)<<endl;return0;}
Exercise 12: Count the Vowels in a String
Write a recursive function that takes a string and returns the total number of vowels (A, E, I, O, U) inside it.
Solution
#include<stdio.h>intcountVowels(charstr[],intindex){if(str[index]=='\0'){return0;}charch=str[index];intisVowel=(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')?1:0;returnisVowel+countVowels(str,index+1);}intmain(){charstr[100];printf("Enter a string: ");scanf("%s",str);printf("Number of vowels: %d\n",countVowels(str,0));return0;}
#include<iostream>usingnamespacestd;intcountVowels(charstr[],intindex){if(str[index]=='\0'){return0;}charch=str[index];intisVowel=(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')?1:0;returnisVowel+countVowels(str,index+1);}intmain(){charstr[100];cout<<"Enter a string: ";cin>>str;cout<<"Number of vowels: "<<countVowels(str,0)<<endl;return0;}
Exercise 13: Check if an Array is Sorted
Write a recursive function that takes an array of numbers and returns True if it is sorted in ascending order, and False if it isn’t.
Solution
#include<stdio.h>intisSorted(intarr[],intsize){if(size==0||size==1)return1;if(arr[size-1]<arr[size-2])return0;returnisSorted(arr,size-1);}intmain(){intsize;printf("Enter number of elements: ");scanf("%d",&size);intarr[size];printf("Enter elements: ");for(inti=0;i<size;i++){scanf("%d",&arr[i]);}if(isSorted(arr,size)){printf("Array is sorted.\n");}else{printf("Array is not sorted.\n");}return0;}
#include<iostream>usingnamespacestd;boolisSorted(intarr[],intsize){if(size==0||size==1)returntrue;if(arr[size-1]<arr[size-2])returnfalse;returnisSorted(arr,size-1);}intmain(){intsize;cout<<"Enter number of elements: ";cin>>size;intarr[size];cout<<"Enter elements: ";for(inti=0;i<size;i++){cin>>arr[i];}if(isSorted(arr,size)){cout<<"Array is sorted."<<endl;}else{cout<<"Array is not sorted."<<endl;}return0;}
Exercise 14: Binary to Decimal Conversion
Write a recursive function that takes a binary string and returns its decimal equivalent (e.g., "1010" becomes 10).
Solution
#include<stdio.h>
#include<math.h>intbinaryToDecimal(charbinary[],intlength,intpower){if(length==0)return0;intbit=binary[length-1]-'0';returnbit*(int)pow(2,power)+binaryToDecimal(binary,length-1,power+1);}intmain(){charbinary[100];printf("Enter a binary number: ");scanf("%s",binary);intlength=0;while(binary[length]!='\0'){length++;}printf("Decimal representation: %d\n",binaryToDecimal(binary,length,0));return0;}
#include<iostream>
#include<cmath>usingnamespacestd;intbinaryToDecimal(charbinary[],intlength,intpower){if(length==0)return0;intbit=binary[length-1]-'0';returnbit*(int)pow(2,power)+binaryToDecimal(binary,length-1,power+1);}intmain(){charbinary[100];cout<<"Enter a binary number: ";cin>>binary;intlength=0;while(binary[length]!='\0'){length++;}cout<<"Decimal representation: "<<binaryToDecimal(binary,length,0)<<endl;return0;}
Exercise 15: Count Subsequences with Target Sum
Write a recursive function CountSubsequences() that receives an integer array, its size, current index, current running sum, and a target sum. The function should calculate and return the number of subsequences (contiguous or non-contiguous) of the array whose elements add up to the target sum.
In main(), read the number of elements and fill the array. Then read the target sum, call the recursive function, and print the resulting count.
Example:
Enter number of elements: 3
Enter 3 elements: 1 2 3
Enter target sum: 3
Number of subsequences: 2
Solution
#include<stdio.h>intCountSubsequences(intarr[],intsize,intindex,intcurrentSum,inttargetSum){if(index==size){returncurrentSum==targetSum?1:0;}inttake=CountSubsequences(arr,size,index+1,currentSum+arr[index],targetSum);intdontTake=CountSubsequences(arr,size,index+1,currentSum,targetSum);returntake+dontTake;}intmain(){intsize,targetSum;intarr[50];printf("Enter number of elements: ");scanf("%d",&size);printf("Enter %d elements: ",size);for(inti=0;i<size;i++){scanf("%d",&arr[i]);}printf("Enter target sum: ");scanf("%d",&targetSum);intcount=CountSubsequences(arr,size,0,0,targetSum);printf("Number of subsequences: %d\n",count);return0;}
#include<iostream>usingnamespacestd;intCountSubsequences(intarr[],intsize,intindex,intcurrentSum,inttargetSum){if(index==size){returncurrentSum==targetSum?1:0;}inttake=CountSubsequences(arr,size,index+1,currentSum+arr[index],targetSum);intdontTake=CountSubsequences(arr,size,index+1,currentSum,targetSum);returntake+dontTake;}intmain(){intsize,targetSum;intarr[50];cout<<"Enter number of elements: ";cin>>size;cout<<"Enter "<<size<<" elements: ";for(inti=0;i<size;i++){cin>>arr[i];}cout<<"Enter target sum: ";cin>>targetSum;intcount=CountSubsequences(arr,size,0,0,targetSum);cout<<"Number of subsequences: "<<count<<endl;return0;}