Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Data Structures Using C++ Author: D.S. Malik(text book) 1) Sum of numbers Write

ID: 3796043 • Letter: D

Question

Data Structures Using C++ Author: D.S. Malik(text book) 1) Sum of numbers Write a recursive function that accepts an integer argument and returns the sum of all the integers from 1 up to the number passed as an argument. For example, if 50 is passed as an argument, the function will return the sum of 1, 2, 3, 4, 50. 2) Counting of times a character appears in a string int main() string str abcddddef "The letter 'd' appears ut rs ('d', str, 0) times. An": nul system ("PAUSE"); return 0 Write the recursive function (called above) that counts the number of times the character searched (d') appears in the string str. Be sure to include comments Use meaningful identifier names (constants where appropriate) Do not work together, no two people should have identical work!?!? Turn in .cpp file (select the "print command from bloodshed) Turn in a "print-screen' of your output (press 'print-screen' on keyboard, then paste in MS-Word)

Explanation / Answer

1.

#include <iostream>

using namespace std;

// function to find sum till n
int findSum(int n)
{
// base case to return sum as 1 when number is 1 in recursive call
if (n == 1) return 1;
else
// find sum using recursion by suming current number and finding sum off all number from 1 to 1 less than n
return n + findSum(n-1);
}

int main()
{
int sum = findSum(50);
cout << "Sum till 50 is : " << sum <<endl;
return 0;
}

2.

#include <iostream>

using namespace std;

// function to count d in str. Start indicate position of str still unprocessed
int numChars(char d, string str, int start)
{
// check till length of string only one char at a time
if (start < str.length())
{
int count = 0;
// if char is d then recurse by adding 1
if (str[start] == d)
{
return 1 + numChars(d, str, start+1);
}
else // recurse without adding 1
{
return numChars(d, str, start+1);
}

}
else // if string is completely traversed return
{
return 0;
}
}

int main()
{
string str = "abcddddef";
cout << "The letter 'd' appears "
<< numChars('d', str, 0) << " times. ";

return 0;
}