Create a method that uses a loop to calculate the summation. Should have the sam
ID: 3784959 • Letter: C
Question
Create a method that uses a loop to calculate the summation. Should have the same signature as the recursive method below but use a loop instead
int sum(int n)
{
if (n < 1)
{
return 0;
}
return sum(n-1) + n;
}
I need help getting the declarations to work, rather can someone help me declare the int sum (int n) I dont know how to declare that function so everytime I run the program it just crashes because of the invalid syntax
____________________________________________________________________________________________________________________________________________
int main()
{
int n;
cout << "Enter your 'n' Value "; //allows user to input the value they want
cin >> n;
int sum(int n); // This calls the function sum(int), and then ";" ends the function
{ // This doesnt do anything, invalid syntax
int returnsum = 0;
for (int i = 1; i <= n; i++)
{
returnsum += i;
}
return returnsum;
}
system("pause");
}
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= n; ++i) {
sum += i;
}
cout << "Sum = " << sum;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.