COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
ex1.cpp
Go to the documentation of this file.
1#include <iostream>
2
3using namespace std;
4
5// a function to return the pointer to the maximum element of an array
6int * maxElementPtr(int a[], int num)
7{
8 int max = a[0];
9 int *ptr = &(a[0]);
10
11 for (int i = 0; i < num; ++i) {
12 if (a[i]>max) {
13 ptr = &(a[i]);
14 max = a[i];
15 }
16 }
17 return ptr;
18}
19
20
21
22// a function to return the index to the maximum element of an array
23int maxElement(int a[], int num)
24{
25 int max = a[0], idx=0;
26 for (int i = 0; i < num; ++i) {
27 if (a[i]>max) {
28 idx = i;
29 max = a[i];
30 }
31 }
32 return idx;
33}
34
35
36int main()
37{
38 int m[] = {0, 4, 5, 2, 6, 9, 1};
39
40 int idx = maxElement(m, 7);
41 cout << "idx: " << idx << " element: " << m[idx] << endl;
42
43 int * ptr = maxElementPtr(m, 7);
44 cout << "max element: " << *ptr << endl;
45
46
47 return 0;
48}
int maxElement(int a[], int num)
Definition ex1.cpp:23
int * maxElementPtr(int a[], int num)
Definition ex1.cpp:6
int main()
Definition ex1.cpp:36