-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path33_Passing_Arrays_or_Vectors_to_Functions.cpp
More file actions
55 lines (48 loc) · 1.58 KB
/
33_Passing_Arrays_or_Vectors_to_Functions.cpp
File metadata and controls
55 lines (48 loc) · 1.58 KB
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
#include <iostream>
#include <vector>
using namespace std;
//Also can pass arrays or vectors to a function as argument
//CStrings can be passed to a function like arrays => void myFunc (myStr[n][m]) or void myFunc (myStr *)
//For CPP strings => void myFunc (string)
//double summation(int numbers[]){...}
double summation(vector<float> numbers){
double sum = 0;
int len;
len = numbers.size();
for (int i=0; i<len; i++){
sum += numbers[i];
}
return sum;
}
//a function can be used inside another function, only if is defined above.
void average(vector<float> numbers){
double sum;
sum = summation(numbers); //using another function
int len;
len = numbers.size();
cout << len << endl;
cout << "Average = " << sum/len << endl;
}
//It is possible to making a function call itself. This technique is called recursion.
//Recursion provides a way to break complicated problems down into simple problems which are easier to solve.
//Example: Adding a range of numbers using recursion.
int sum(int n){
//A recursive function
if(n>0) return n + sum(n-1);
else return 0;
//Recursive functions must have a termination condition.
}
int main(){
vector<float> numbers = {15.5, 14.75, 20, 19.25, 17};
average(numbers);
int n = 4;
int s = sum(n); //Calling a recursive function
cout << 1 << " + ... + " << n-1 << " + " << n << " = " << s << endl;
/*
4 + sum(3)
4 + (3 + sum(2))
4 + (3 + (2 + sum(1)))
4 + (3 + (2 + (1 + sum(0))))
==> 4 + 3 + 2 + 1 + 0
*/
}