-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClass712.cpp
executable file
·67 lines (51 loc) · 1.3 KB
/
Class712.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//============================================================================
// Name : Class712.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
int sum(int n) {
int total = 0;
//Version 1 -- loop
// for (int i = 1; i <= n; i++) {
// total += i;
// }
while (n > 0) {
total += n;
n--;
}
//Version 2 -- closed form
//total = n * (n + 1) / 2; //watch out for integer division
//Version 3 -- recursion
// if (n == 0) {
// return 0;
// } else {
// total = sum(n-1) + n;
// return total;
// }
return total;
}
int main() {
int val;
do {
cout << "Enter (neg to stop): ";
cin >> val;
if (val < 0) break;
cout << "val: " << val << endl;
cout << "Result: " << sum(val) << endl << endl;
cout << "val: " << val << endl;
/*
* The call-by-value parameter passing mechanism is used
* when calling the sum function. Consequently, the value of
* the variable 'val' does not change, even the corresponding
* parameter 'n' in the function is modified.
*/
// if (val >= 0) {
// cout << "Result: " << sum(val) << endl << endl;
// }
} while (true);// (val >= 0);
return 0;
}