Get, Set, Avg, Max
int main() {
struct Array arr = {{2, 3, 4, 5, 6}, 10, 5};
Display(arr);
return 0;
}
Get
One thing to take care about: it is to check whether the index given is valid or not. It should not be greater or equal to length and it should not be less than zero.
int Get(struct Array arr, int index) {
if (index >= 0 && index < arr.length) {
return arr.A[index];
}
return -1;
}
Set
This method is to replace / overwrite a value at a particular index. We should again check whether the index is valid or not.
void Set(struct Array *arr, int index, int x) {
if (index >= 0 && index < arr->length) {
arr->A[index] = x;
}
}
Time taken by both methods is constant.
Max
You have to go through all the elements once, so the operation is O(n).
int Max(struct Array arr) {
int max = arr.A[0];
int i;
for (i = 1; i < arr.length; i++) {
if (arr.A[i] > max)
max = arr.A[i];
}
return max;
}
Min
Very similar to the max operation.
int Min(struct Array arr) {
int min = arr.A[0];
int i;
for (i = 1; i < arr.length; i++) {
if (arr.A[i] < min)
min = arr.A[i];
}
return min;
}
Sum
For finding the total of all the elements, I should traverse through all the elements, and go on adding them to some variable that's total.
We are scanning through all the elements one by one, and we are going on adding them to total. So for all elements, it's O(n).
int Sum(struct Array arr) {
int total = 0;
int i;
for (i = 0; i < arr.length; i++) {
total += arr.A[i];
}
return total;
}
We can also write it recursively.
0 if n < 0
Sum(A, n) = Sum(A, n - 1) + A[n] if n >= 0
int Sum(struct Array arr, int n) {
if (n < 0)
return 0;
else
return Sum(arr.A, n - 1) + arr.A[n];
}
// call: sum(A, length - 1);
Avg
Average is nothing but sum of all the elements, divided by number of elements.
float Avg(struct Array arr) {
return (float)Sum(arr) / arr.length;
}