Answered step by step
Verified Expert Solution
Link Copied!

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 //

image text in transcribedimage text in transcribedimage text in transcribed

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Practical Database Programming With Visual C# .NET

Authors: Ying Bai

1st Edition

0470467274, 978-0470467275

More Books

Students also viewed these Databases questions

Question

3.What are the Importance / Role of Bank in Business?

Answered: 1 week ago

Question

How do modern Dashboards differ from earlier implementations?

Answered: 1 week ago