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
#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;
}
Comments
Leave a comment