Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
function fun(unsigned integer n)
begin
    result = 1
    while n != 0
    n = n - 1
    result = result + 2 * n
  end while
  return result
end

Assume that n > 0. What is the result computed by fun?

options:
A 2^n
B 2n − 1
C 2n − 2
*D n^2 − n + 1 (answer)
E n^2

What I have tried:

I have tried recursion. but don't understand this code.
Posted
Updated 1-Dec-21 21:38pm
v2
Comments
Richard Deeming 2-Dec-21 3:52am    
Funny - that code doesn't look anything like C, C++, or Java to me. Why have you tagged your question with three completely irrelevant tags?

1 solution

First off, indent your code correctly - it makes it a lot easier to see what is goign on:
function fun(unsigned integer n)
begin
    result = 1
    while n != 0
        n = n - 1
        result = result + 2 * n
    end while
    return result
end

Second, you only get recursion when a function directly or indirectly calls itself, as in the classic Factorial example:
function Factorial(int n)
begin
   if (n <= 1) return 1
   return n * Factorial(n - 1)
end

Your code doesn't do that, so it isn't recursive.

Instead it uses a loop, reducing the value of n each time round the loop, and exiting the loop only when n has reached zero.

So look at the code and generate each term that is added to result each time you go round. Write them down on a piece of paper, and it should be pretty obvious what it is doing, and how it works.

This is a simple bit of code, and you should be able to analyse it for yourself with a bit of effort - and that starts you "thinking the right way" about analysing more complex tasks. If we do that stage for you, it means you don't learn how to do that, and future tasks will become much harder as a result!
 
Share this answer
 
Comments
Nobel Fix 2-Dec-21 3:44am    
thank you
OriginalGriff 2-Dec-21 4:50am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900