You are here:

C++/write a do-while loop to calculate total

Advertisement


Question
Hi! Its me again. I need to write a function total and need to use a do-while loop to calculate the sum from 1 to n.

I wrote:
int total (int n)
{
  n = 1;
  do
  {
     total = n + n++;
        cout << total << endl;
  }
} while (n > 0);

Answer
Dear Mr Ravi !

A small effort will sure bring solution to your problem ,just understanding the problem and language constructs matters

int total(int n)
{
  int i = 1;
  int sum = 0;
  while (  i <= n )
     sum+=i++;
  return sum;
}

i haven't tested this code  , so i kindly request you to report me in case of issues

Thanks and Regards!
Prince M. Premnath

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise

Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)

Experience

More than 5 years

Education/Credentials
MCA

©2016 About.com. All rights reserved.