Eeeee
Eeeee
GGGB
int main() {
// Create a sample linked list
Node* head = new Node{1, nullptr};
head->next = new Node{2, nullptr};
head->next->next = new Node{3, nullptr};
head->next->next->next = new Node{4, nullptr};
// Don't forget to free the memory allocated for the linked list.
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
}
return 0;
}
As a result, the output would not reverse the characters as intended, and we might get duplicate
characters in the output. The exact output would depend on the input and the number of recursive
calls. In most cases, it would not produce the desired reversed output.
Q:5: Write a recursive method that for a positive integer n prints odd numbers
a. between 1 and n
b. between n and 1
ANS: To print odd numbers between 1 and a positive integer `n` and between `n` and 1 using a
recursive method, we can define two separate functions. Here's how we can do it:
#include <iostream>
void printOddNumbersFrom1ToN(int n) {
if (n < 1) {
return;
}
if (n % 2 == 1) {
std::cout << n << " ";
}
printOddNumbersFrom1ToN(n - 1);
}
int main() {
int n;
std::cout << "Enter a positive integer (n): ";
std::cin >> n;
std::cout << "Odd numbers between 1 and " << n << ": ";
printOddNumbersFrom1ToN(n);
std::cout << std::endl;
return 0;
}
This code defines a `printOddNumbersFrom1ToN` function that recursively prints odd numbers
from `n` down to 1.
#include <iostream>
void printOddNumbersFromNTo1(int n) {
if (n < 1) {
return;
}
if (n % 2 == 1) {
std::cout << n << " ";
}
printOddNumbersFromNTo1(n - 1);
}
int main() {
int n;
std::cout << "Enter a positive integer (n): ";
std::cin >> n;
std::cout << "Odd numbers between " << n << " and 1: ";
printOddNumbersFromNTo1(n);
std::cout << std::endl;
return 0;
}
This code defines a `printOddNumbersFromNTo1` function that recursively prints odd numbers
from `n` down to 1.
We can choose which part of the code to use based on whether we want to print odd numbers
from 1 to `n` or from `n` to 1.
Q:6: Write a recursive method that for a positive integer returns a string with commas
in the appropriate places, for example, putCommas(1234567) returns the string
“1,234,567.”
ANS: We can create a recursive method in C++ to insert commas in the appropriate places for a
positive integer. Here's one way to do it:
#include <iostream>
#include <string>
std::string putCommas(int num) {
if (num < 1000) {
// Base case: If the number is less than 1000, simply convert it to a string and return.
return std::to_string(num);
} else {
// Recursive case: Split the number into two parts - the last three digits and the rest.
int lastThreeDigits = num % 1000;
int restOfTheNumber = num / 1000;
// Recursively format the rest of the number and add commas to the last three digits.
std::string formattedRest = putCommas(restOfTheNumber);
std::string formattedLastThree = std::to_string(lastThreeDigits);
// Combine the two parts with a comma in the middle and return.
return formattedRest + "," + (formattedLastThree.length() == 1 ? "00" + formattedLastThree :
(formattedLastThree.length() == 2 ? "0" + formattedLastThree : formattedLastThree));
}
}
int main() {
int number;
std::cout << "Enter a positive integer: ";
std::cin >> number;
if (number >= 0) {
std::string result = putCommas(number);
std::cout << "Formatted number with commas: " << result << std::endl;
} else {
std::cout << "Please enter a non-negative integer." << std::endl;
}
return 0;
}
This code defines a `putCommas` function that recursively inserts commas into a given positive
integer. It separates the number into the last three digits and the rest and recursively formats the
rest. The function returns a string with commas in the appropriate places.
Q:7: Write a recursive method to print a Syracuse sequence that begins with a number n0
and each element ni
#include <iostream>
void printSyracuseSequence(int n) {
if (n == 1) {
std::cout << n << std::endl;
} else {
std::cout << n << " ";
if (n % 2 == 0) {
// If n is even, calculate ni-1 / 2 and recurse with the result.
printSyracuseSequence(n / 2);
} else {
// If n is odd, calculate 3ni-1 + 1 and recurse with the result.
printSyracuseSequence(3 * n + 1);
}
}
}
int main() {
int n0;
std::cout << "Enter a starting number (n0): ";
std::cin >> n0;
if (n0 <= 0) {
std::cout << "Please enter a positive integer for n0." << std::endl;
} else {
std::cout << "Syracuse sequence for " << n0 << ": ";
printSyracuseSequence(n0);
}
return 0;
}
In this code:
- The `printSyracuseSequence` function takes an integer `n` and recursively calculates the Syracuse
sequence until it reaches 1, printing each element in the sequence.
- Otherwise, it prints the current number, and based on whether it's even or odd, it calculates the
next number in the sequence and recursively calls `printSyracuseSequence` with that number.
- The main function takes the starting number `n0` as input and initiates the Syracuse sequence for
that number.
This code will print the Syracuse sequence starting from the given `n0` and ending with 1.
Q:8: Write a recursive method that uses only addition, subtraction, and comparison to
multiply two numbers.
ANS: We can implement a recursive method to multiply two numbers using only addition,
subtraction, and comparison. One common algorithm for this is the Russian Peasant Multiplication
method. Here's a C++ implementation:
#include <iostream>
// If 'b' is odd, subtract 'a' from the result and recursively multiply 'a' and 'b' by halving 'b'.
if (b % 2 == 1) {
return a + multiply(a, b - 1);
}
// If 'b' is even, double 'a' and halve 'b' to recursively multiply.
else {
return multiply(a * 2, b / 2);
}
}
int main() {
int num1, num2;
std::cout << "Enter two numbers to multiply: ";
std::cin >> num1 >> num2;
return 0;
}
In this code:
- The `multiply` function recursively calculates the product of two numbers `a` and `b`.
- If one of the numbers is 0, the function returns 0 (base case).
- If `b` is odd, it subtracts `a` from the result and recursively multiplies `a` by reducing `b` by 1.
- If `b` is even, it doubles `a` and reduces `b` by half and recursively multiplies.
- The main function takes two numbers as input and calls the `multiply` function to compute the
product.
This recursive algorithm effectively multiplies two numbers using only addition, subtraction, and
comparison.
Q:9: Write a recursive function to compute the binomial coefficient according to the
definition:
C(n, k) = 1 if k is 0 or k is equal to n.
C(n, k) = C(n - 1, k - 1) + C(n - 1, k) otherwise.
ANS: We can compute the binomial coefficient using a recursive function according to the given
definition. The binomial coefficient, denoted as C(n, k), can be calculated as follows:
C(n, k) = 1 if k is 0 or k is equal to n.
C(n, k) = C(n - 1, k - 1) + C(n - 1, k) otherwise.
Here's a C++ implementation of a recursive function to compute the binomial coefficient based on
this definition:
#include <iostream>
int main() {
int n, k;
std::cout << "Enter values for n and k: ";
std::cin >> n >> k;
if (k < 0 || k > n) {
std::cout << "Invalid input. k must be between 0 and n." << std::endl;
} else {
int result = binomialCoefficient(n, k);
std::cout << "C(" << n << ", " << k << ") = " << result << std::endl;
}
return 0;
}
In this code:
- The `binomialCoefficient` function recursively calculates the binomial coefficient using the
definition provided.
- If k is 0 or k is equal to n, it returns 1 (base case).
- Otherwise, it recursively calculates C(n - 1, k - 1) and C(n - 1, k) and adds them together.
The main function takes input for n and k, performs input validation, and then computes and
prints the binomial coefficient.
Q:10: Write a recursive function to add the first n terms of the series
1 + 1/2 - 1/3 + 1/4 - 1/5....
ANS: We can write a recursive function in C++ to add the first `n` terms of the series 1 + 1/2 - 1/3 +
1/4 - 1/5... Here's how we can do it:
#include <iostream>
if (!isPositive) {
term = -term;
}
double sumSeries(int n) {
if (n < 1) {
std::cerr << "Invalid input. n should be a positive integer." << std::endl;
return 0.0;
}
int main() {
int n;
std::cout << "Enter the number of terms (n): ";
std::cin >> n;
return 0;
}
In this code:
- `calculateSeries` is a recursive function that calculates the sum of the series up to the `n`-th term.
It uses a `currentTerm` to keep track of the current term, `currentSum` to accumulate the sum, and
`isPositive` to determine whether the current term is positive or negative.
- `sumSeries` is a wrapper function that validates the input `n` and initiates the recursive
calculation.
- The `main` function takes input for `n`, checks if it's a valid input, and then calculates and prints
the sum of the series.
This code will compute the sum of the first `n` terms of the series as specified.
Q:11: Write a recursive function GCD(n,m) that returns the greatest common divisor of
two integers n and m according to the following definition:
ANS: We can write a recursive function to calculate the greatest common divisor (GCD) of two
integers `n` and `m` based on the definition we provided. Here's a C++ implementation of such a
function:
#include <iostream>
int main() {
int n, m;
std::cout << "Enter two integers (n and m): ";
std::cin >> n >> m;
if (n < 0 || m < 0) {
std::cerr << "Both n and m should be non-negative integers." << std::endl;
} else {
int result = GCD(n, m);
std::cout << "GCD(" << n << ", " << m << ") = " << result << std::endl;
}
return 0;
}
In this code:
- The `GCD` function calculates the GCD of `n` and `m` using the definition we provided. It checks
whether `m` is less than or equal to `n` and whether `n` is divisible by `m`. If so, it returns `m`. If `n`
is less than `m`, it swaps `n` and `m` and continues the calculation. Otherwise, it recursively
computes the GCD of `m` and `n % m`.
- The `main` function takes input for `n` and `m`, checks if they are non-negative integers, and then
calculates and prints the GCD.
This code will compute the GCD of two integers `n` and `m` based on the provided definition.
#include <iostream>
int main() {
int n;
std::cout << "Enter a positive integer (n): ";
std::cin >> n;
if (n <= 0) {
std::cerr << "Please enter a positive integer." << std::endl;
} else {
std::cout << "Cubes of numbers from 1 to " << n << ": ";
printCubes(n);
std::cout << std::endl;
}
return 0;
}
In this code:
- The `printCubes` function is a recursive function that takes two parameters: `n` (the upper limit)
and `i` (the current number being processed).
- It checks if `i` is less than or equal to `n`. If true, it prints the cube of `i` and makes a recursive call
with `i` incremented by 1.
- The `main` function takes input for `n`, checks if it's a positive integer, and then calls the
`printCubes` function to print the cubes of numbers from 1 to `n`.
This code provides a recursive version of the original `cubes` function that prints the cubes of
numbers from 1 to `n`.
#include <iostream>
#include <cctype>
#include <string>
return false;
}
int main() {
std::string word;
std::cout << "Enter a word to check if it's a palindrome: ";
std::cin >> word;
if (isPalindromeWord(word)) {
std::cout << "It's a palindrome." << std::endl;
} else {
std::cout << "It's not a palindrome." << std::endl;
}
return 0;
}
This code checks if a single word is a palindrome by removing non-alphabet characters and
ignoring case differences.
#include <iostream>
#include <cctype>
#include <string>
return false;
}
int main() {
std::string sentence;
std::cout << "Enter a sentence to check if it's a palindrome: ";
std::getline(std::cin, sentence);
if (isPalindromeSentence(sentence)) {
std::cout << "It's a palindrome." << std::endl;
} else {
std::cout << "It's not a palindrome." << std::endl;
}
return 0;
}
This code checks if a sentence is a palindrome by removing non-alphabet characters, ignoring case
differences, and spaces. It uses recursion to check if the cleaned sentence is a palindrome.
#include <iostream>
if (str[index] == ch) {
return true;
}
int main() {
std::string str;
char ch;
std::cout << "Enter a string: ";
std::cin >> str;
std::cout << "Enter a character to check: ";
std::cin >> ch;
if (isCharacterInString(str, ch)) {
std::cout << "The character is in the string." << std::endl;
} else {
std::cout << "The character is not in the string." << std::endl;
}
return 0;
}
b. Count all occurrences of a character in a string:
#include <iostream>
int main() {
std::string str;
char ch;
std::cout << "Enter a string: ";
std::cin >> str;
std::cout << "Enter a character to count: ";
std::cin >> ch;
return 0;
}
#include <iostream>
#include <string>
if (str[index] == ch) {
str.erase(index, 1); // Remove the character at the current index.
} else {
index++;
}
removeCharacterFromString(str, ch, index);
}
int main() {
std::string str;
char ch;
std::cout << "Enter a string: ";
std::cin >> str;
std::cout << "Enter a character to remove: ";
std::cin >> ch;
removeCharacterFromString(str, ch);
std::cout << "String after removing all occurrences: " << str << std::endl;
return 0;
}
In these examples, we use recursion to check if a character is in a string, count its occurrences, and
remove all occurrences. The last example modifies the original string to remove the character
recursively.
Q:15: Write equivalents of the last three functions for substrings (do not use strstr()).
ANS: To perform operations with substrings without using the `strstr()` function, we can
create custom recursive functions to:
bool isSubstringInString(const std::string& str, const std::string& substr, int strIndex = 0, int
substrIndex = 0) {
if (substrIndex == substr.length()) {
return true; // Entire substring has been found.
}
if (strIndex == str.length()) {
return false; // Reached the end of the string without finding the entire substring.
}
if (str[strIndex] == substr[substrIndex]) {
// Recurse with both indices incremented.
return isSubstringInString(str, substr, strIndex + 1, substrIndex + 1);
} else {
// Start searching for the substring from the next position in the string.
return isSubstringInString(str, substr, strIndex - substrIndex + 1, 0);
}
}
int main() {
std::string str;
std::string substr;
std::cout << "Enter a string: ";
std::cin >> str;
std::cout << "Enter a substring to check: ";
std::cin >> substr;
if (isSubstringInString(str, substr)) {
std::cout << "The substring is in the string." << std::endl;
} else {
std::cout << "The substring is not in the string." << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int countSubstringOccurrences(const std::string& str, const std::string& substr, int strIndex = 0, int
substrIndex = 0) {
if (substrIndex == substr.length()) {
return 1 + countSubstringOccurrences(str, substr, strIndex - substrIndex + 1, 0);
}
if (strIndex == str.length()) {
return 0;
}
if (str[strIndex] == substr[substrIndex]) {
// Continue matching the substring.
return countSubstringOccurrences(str, substr, strIndex + 1, substrIndex + 1);
} else {
// Start searching for the substring from the next position in the string.
return countSubstringOccurrences(str, substr, strIndex - substrIndex + 1, 0);
}
}
int main() {
std::string str;
std::string substr;
std::cout << "Enter a string: ";
std::cin >> str;
std::cout << "Enter a substring to count: ";
std::cin >> substr;
return 0;
}
#include <iostream>
#include <string>
if (strIndex == str.length()) {
return;
}
if (str[strIndex] == substr[substrIndex]) {
// Continue matching the substring.
removeSubstringFromString(str, substr, strIndex + 1, substrIndex + 1);
} else {
// Start searching for the substring from the next position in the string.
removeSubstringFromString(str, substr, strIndex - substrIndex + 1, 0);
}
}
int main() {
std::string str;
std::string substr;
std::cout << "Enter a string: ";
std::cin >> str;
std::cout << "Enter a substring to remove: ";
std::cin >> substr;
removeSubstringFromString(str, substr);
std::cout << "String after removing all occurrences: " << str << std::endl;
return 0;
}
In these examples, we use recursion to work with substrings in a string, checking if a substring is
present, counting its occurrences, and removing all occurrences from the string.\
#include <iostream>
int main() {
int n;
std::cout << "Enter a non-negative integer: ";
std::cin >> n;
if (n < 0) {
std::cerr << "Please enter a non-negative integer." << std::endl;
} else {
unsigned long long result = factorial(n);
std::cout << "Factorial of " << n << " is " << result << std::endl;
}
return 0;
}
This short program calculates the factorial of a non-negative integer using recursion. The `factorial`
function recursively calculates the factorial.