#include<iostream>
using namespace std;
int GetTotal(int n);
void main()
{
int num;
cout<<"We will calculate the total of \n"
<<"the consecutive numbers,\n"
<<"starting from 1 to the number\n"
<<"that you enter."<<endl;
cout<<"\n\nEnter the ending number."<<endl;
cin>>num;
cout<<"\n\nThe sum of 1, 2, ..., "<<num <<" is "
<<GetTotal(num)<<endl<<endl;
}
int GetTotal(int n)
{
//???????????
//Design your own method to calculate the total from 1 to n.
}
Method One: Accumulation Way
int GetTotal(int n)
{
int sum=0; // one action
for(int i=1; i<=n; i++) // one action for initializing, n+1 actions for comparisons, n actions for increment
sum = sum + i; // one action for addition, another action for assignment. Repeat them n times
return sum; // one action
}
// Total time = 1+(1+n+1+n)+n*2+1 = 4n+4 = O(n)
Method Two: Using Mathematical Formulas
int GetTotal(int n)
{
int sum;
sum = (1 + n) * n / 2; //one action for each operator, +,*, /. another action for assignment.
return sum; // one action
}
// Total time = (3 + 1) + 1 = 4 = O(c)