📖 Scenario: Imagine you have a list of daily expenses and you want to find the total amount spent. Instead of adding them one by one using a loop, you will use a special technique called recursion to add them up.
🎯 Goal: Build a recursive function in C++ that calculates the sum of all elements in an integer array.
📋 What You'll Learn
Create an integer array named expenses with exact values: 100, 200, 300, 400, 500
Create an integer variable n that stores the size of the expenses array
Write a recursive function sumArray that takes the array and its size as parameters and returns the sum of its elements
Print the total sum returned by sumArray
💡 Why This Matters
🌍 Real World
Recursion helps solve problems like summing expenses, searching, or processing data step-by-step, similar to breaking a big task into smaller tasks.
💼 Career
Understanding recursion is important for software development roles that involve algorithms, data processing, and problem-solving.
Progress0 / 4 steps
1
Create the array of expenses
Create an integer array called expenses with these exact values: 100, 200, 300, 400, 500
DSA C++
Hint
Use curly braces {} to list the values inside the array.
2
Store the size of the array
Create an integer variable called n and set it to the size of the expenses array using sizeof(expenses) / sizeof(expenses[0])
DSA C++
Hint
Use sizeof to find the total bytes and divide by one element's size.
3
Write the recursive function to sum the array
Write a recursive function called sumArray that takes parameters int arr[] and int size. It should return 0 if size is 0. Otherwise, return the last element arr[size - 1] plus the result of sumArray(arr, size - 1)
DSA C++
Hint
Base case: when size is 0, return 0. Recursive case: add last element to sum of rest.
4
Print the total sum of the expenses
Print the result of calling sumArray(expenses, n) using std::cout with the message Total expenses:
DSA C++
Hint
Use std::cout to print the message and the sum.
Practice
(1/5)
1. What does a recursive function on an array typically do to process the array elements?
easy
A. It processes one element and calls itself on the rest of the array
B. It processes all elements at once without calling itself
C. It uses loops instead of calling itself
D. It only processes the last element of the array
Solution
Step 1: Understand recursion on arrays
A recursive function on an array usually handles one element and then calls itself on the remaining elements.
Step 2: Compare options
It processes one element and calls itself on the rest of the array matches this behavior. Options A, C, and D describe non-recursive or incorrect methods.
Final Answer:
It processes one element and calls itself on the rest of the array -> Option A
Quick Check:
Recursion on arrays = process one element + recurse [OK]
Hint: Remember recursion breaks problem into smaller parts [OK]
Common Mistakes:
Thinking recursion processes all elements at once
Confusing recursion with loops
Assuming recursion only processes last element
2. Which of the following is the correct base case for a recursive function that sums elements of an integer array arr of size n?
easy
A. if (n == 0) return 0;
B. if (n == 1) return arr[1];
C. if (arr == NULL) return 0;
D. if (n < 0) return 0;
Solution
Step 1: Identify base case for recursion on array size
The base case should stop recursion when no elements are left, which is when n == 0.
Step 2: Check each option
if (n == 0) return 0; returns 0 when n == 0, which is correct. if (n == 1) return arr[1]; incorrectly accesses arr[1] instead of arr[0]. if (arr == NULL) return 0; checks pointer but not size. if (n < 0) return 0; uses invalid negative size.
Final Answer:
if (n == 0) return 0; -> Option A
Quick Check:
Base case for empty array = return 0 [OK]
Hint: Base case usually when size is zero [OK]
Common Mistakes:
Using wrong index in base case
Checking pointer instead of size
Allowing negative sizes
3. What is the output of the following C++ code?
int sumArray(int arr[], int n) {
if (n == 0) return 0;
return arr[n-1] + sumArray(arr, n-1);
}
int main() {
int arr[] = {1, 2, 3, 4};
int result = sumArray(arr, 4);
std::cout << result;
return 0;
}
Hint: Sum recursion adds last element + sum of rest [OK]
Common Mistakes:
Confusing index n-1 with n
Forgetting base case returns 0
Assuming sum is product
4. Find the error in this recursive function that counts occurrences of character c in string s:
int countChar(string s, char c, int index) {
if (index == s.length()) return 0;
if (s[index] == c) return 1 + countChar(s, c, index++);
else return countChar(s, c, index++);
}
medium
A. Missing check for empty string
B. Base case condition is wrong
C. Using post-increment (index++) causes infinite recursion
D. Function should return bool, not int
Solution
Step 1: Analyze recursive calls with index++
Using index++ passes the current index value before increment, so recursive call uses same index repeatedly.
Step 2: Identify infinite recursion cause
Because index does not increase in recursive calls, base case is never reached, causing infinite recursion.
Final Answer:
Using post-increment (index++) causes infinite recursion -> Option C
Quick Check:
Post-increment in recursion argument = infinite loop [OK]
Hint: Use pre-increment (++index) or index+1 in recursion call [OK]
Common Mistakes:
Using post-increment in recursive call argument
Ignoring base case correctness
Confusing return types
5. Given a string s, write a recursive function to check if it is a palindrome (reads same forward and backward). Which approach below correctly implements this?
hard
A. Reverse string using loop and compare with original
B. Check if first and last chars match, then recurse on substring excluding them
C. Count matching characters from start only
D. Use recursion to count characters and compare counts
Solution
Step 1: Understand palindrome check recursively
To check palindrome recursively, compare first and last characters; if they match, recurse on substring excluding them.
Step 2: Evaluate options
Check if first and last chars match, then recurse on substring excluding them matches this logic. Reverse string using loop and compare with original uses loops, not recursion. Options C and D do not correctly check palindrome property.
Final Answer:
Check if first and last chars match, then recurse on substring excluding them -> Option B