-
Notifications
You must be signed in to change notification settings - Fork 0
/
PassingArraysToFunctions.cpp
65 lines (55 loc) · 1.9 KB
/
PassingArraysToFunctions.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
/**************************************************************************************************************
Author: Francesca Nannizzi
Contact: [email protected]
Distributed March 2013
***************************************************************************************************************
This program demonstrates two methods for handling arrays within functions.
**************************************************************************************************************/
#include <iostream>
using namespace std;
// This function stores the scores + 5 in a new array
// and passes a pointer to the array back to main.
int* add5toScores(int scores[], int size) { // notice this returns type int*
int * temp = new int[size];
if(size > 0){
for (int i = 0; i < size; i++){
temp[i] = scores[i] + 5;
}
}
return temp;
}
// This function subtracts 5 from the array passed in
// which is passed by reference by default.
void subtract5FromScores(int scores[], int size) {
if (size > 0){
for (int i = 0; i < size; i++){
scores[i] = scores[i] - 5;
}
}
}
int main(){
int scoreArray[10] = {10,20,30,40,50,60,70,80,90,100};
// Print out the original array
cout << endl;
cout << "Original scores: " << endl;
for(int i = 0; i < 10; i++){
cout << "Score: " << i << " = " << scoreArray[i] << endl;
}
cout << endl;
// Initialize a pointer to a new array of scores + 5
int* tempPointer = add5toScores(scoreArray,10);
cout << "After add function: " << endl;
for(int i = 0; i < 10; i++){
// Increments the pointer, then dereferences it
cout << "Score: " << i << " = " << *(tempPointer + i) << endl;
}
cout << endl;
// Edit the original array to scores - 5
subtract5FromScores(scoreArray,10);
cout << "After subtract function: " << endl;
for(int i = 0; i < 10; i++){
cout << "Score: " << i << " = " << scoreArray[i] << endl;
}
cout << endl;
return 0;
}