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
3
using namespace
std;
4
5
// a function to return the pointer to the maximum element of an array
6
int
*
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
23
int
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
36
int
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
}
maxElement
int maxElement(int a[], int num)
Definition
ex1.cpp:23
maxElementPtr
int * maxElementPtr(int a[], int num)
Definition
ex1.cpp:6
main
int main()
Definition
ex1.cpp:36
Module8
Sample Code
Exercise Solution
ex1.cpp
Generated on Sun Sep 29 2024 16:39:53 for COMP2113 by
1.12.0