Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Here is one way of calculating 1+2+...+n: // Pre-condition: n is 1 or greater // Post-condition: this functions returns the value of // 1+2+3+...+n //
Here is one way of calculating 1+2+...+n: // Pre-condition: n is 1 or greater // Post-condition: this functions returns the value of // 1+2+3+...+n // Examples: sum(1) is 1, sum(2) is 3, sum(3) is 6. ... int sum (int n) int sum = 0; while (n > 0) { sum sum + n; --n; } return sum; } Each question below will use the same header, so all you need to write is the code that would appear in the function body. Do not change the function header, or the behavior of the function. a) Rewrite the body of the sum function using a single for-loop instead of a while-loop. b) Rewrite the body of the sum function using a single do-while loop instead of a while-loop. (4 marks) c) Rewrite the body of the sum function using recursion instead of a while-loop. (4 marks) d) Rewrite the body of the sum function using no loops or recursion. [hints: 1+2+3+4+.....+n= n(n+1)/2] (6 marks)
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started