Answer to Question #335954 in C++ for GANIZANI

Question #335954

The function below calculates and returns the sum of integers between 1 and n (inclusive) where n is an integer accepted by the function i.e.

If n = 3;

then the function returns 6 (1+2+3). int sum(int n) { int sum = 0;

while (n > 0) { sum = sum + n; --n; } return sum;

}


Rewrite the body of the sum function using a single do-while loop instead of a while-loop


1
Expert's answer
2022-05-02T13:37:40-0400
#include <iostream>
using namespace std;

int sumN(int);

int main() {
 int n;
 
 cout<<"N: ";
 cin>>n;
 if(n>0){
     cout<<sumN(n)<<endl;
 }
 
  return 0;
}

int sumN(int n){
    int sum=0;
    
    do{
     sum = sum + n;
     --n;    
        
    }while (n > 0);
    
     return sum;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS