1: //timing_summation3.cpp
2: //Finds the sum of integers over a given range.
3: //Allows us to measure the *relative* time taken to sum the integers
4: //over ranges of various sizes by introducing an artificial delay into
5: //each step of the computation.
7: #include <iostream>
8: #include <ctime>
9: using namespace std;
11: int main()
12: {
13: cout << "\nThis program computes the sum of all integers in a "
14: "user-chosen range, and\nattempts to compute as well the time "
15: "taken to perform the summation.";
16: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
18: cout << "\nEnter the smaller integer, then the larger: ";
19: int small, large;
20: cin >> small >> large; cin.ignore(80, '\n'); cout << endl;
22: int sum = 0;
23: clock_t startTime = clock();
24: for (int numberToAdd = small; numberToAdd <= large; numberToAdd++)
25: {
26: sum += numberToAdd;
27: for (int i = 1; i <= 100000; i++)
28: ; /* Do nothing ... */
29: }
30: clock_t endTime = clock();
32: cout << "The sum of all integers from " << small << " to "
33: << large << " (inclusive) is " << sum << ".\n";
34: cout << "The amount of time taken to add them up was "
35: << double(endTime - startTime)/CLOCKS_PER_SEC << " seconds.";
36: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
37: }