Sunday, July 12, 2009

C++ Extra Credit?

The following formula evaluates the sum of the first n integers:


1+2+3+...+n=n(n+1)/2


Write a program that gives separate output for the values n*(n+1)/2 and sumToN(n), which is the recursive funciton in Example 3-11 that sums the first n integers. Output for n=1 to n=10





Example 3-11





Pass the string argument str= "Hello" to recurxive function f().





void f (const strings%26amp; s, int i)





{


if (i %26lt; s.length())


{


cout %26lt;%26lt; s[i];


f(s, i+1);


}


}





a) what is the output from the funciton call f(str, 0)?


b) what is the output from the function call f(str, 3)


c) what is the output for the calls to f() in parts (a) and (b) if f(s ,i+1) comes before cout %26lt;%26lt; s[i]?





Please give comments so I can understand what's goin on.


Thanks

C++ Extra Credit?
So, in c++ to output the result of the formula, then do the following:





int n = 0;


cin %26gt;%26gt; n;


cout %26lt;%26lt; (n * (n + 1)) / 2;





Now, to write a recursive function that sums up the numbers, do the following:





cout %26lt;%26lt; sumToN(n);


int sumToN(int n)


{


if (n == 0)


return 0;


else


return n + sumToN(n-1);


}





Now, let's explain what the recursive function is doing. First, if n is equal to zero, then the answer has to be zero and that's why the function returns zero in that case.





Let's try to understand the "else" part of the function. It says:


"return n + sumToN(n-1);"





Let's say that n in our case is 4. The function does the following:





1) return 4 + sumToN(3);


// the function has to calculate sumToN(3) first before returning





2) return 4 + 3 + sumToN(2);


// the function has to calculate sumToN(2) first before returning





3) return 4 + 3 + 2 + sumToN(1);


// the function has to calculate sumToN(1) first before returning





4) return 4 + 3 + 2 + 1 + sumToN(0);


// the function has to calculate sumToN(0) first before returning





5) return 4 + 3 + 2 + 1 + 0;


// the function can now sum up the numbers and return the result.





I hope this helps


No comments:

Post a Comment