Lab Zero ArrayMaxMin

#### Solution for finding the greatest and smallest numbers in an integer array.

Things to learn from this program:

1. Observe how the program is divided into functions and how these functions are called from main()
2. Understand where the program execution starts and where it ends
3. Understand how to iterate over arrays using for and while loops
4. Understand how to pass an array to a function
```/* arrayMaxMin.cpp */

#include <iostream>
using namespace std;

//function prototype declarations
int findSmallest(int arr[], int arrsize);
int findLargest(int arr[], int arrsize);
void printArray(int arr[], int arrsize);

int main() {
int arr[] = {5, 9, 2, 7, 3 , 6};

int smallest = findSmallest(arr, 6);
int largest = findLargest(arr, 6);

printArray(arr, 6);
cout << "Smallest element in arrray is : "<< smallest << endl;
cout << "Largest element in arrray is : "<< largest << endl;

cout << "Press ENTER to exit" << endl;
cin.get();
//system("PAUSE"); //this works only on Windows as it calls the pause.exe
}

/* function to find and return the smallest number in an int array */
int findSmallest(int arr[], int arrsize) {
int smallest = arr[0]; //assume that the first element is the smallest

for(int i = 0; i < arrsize; i++) {
if (arr[i] < smallest)  //check the smallest with every element in arr
smallest = arr[i];  //if the element is smaller replace smallest
}

return smallest;
}

/* function to find and return the largest number in an int array */
int findLargest(int arr[], int arrsize) {
int largest = arr[0];

for(int i = 0; i < arrsize; i++) {
if (arr[i] > largest)
largest = arr[i];
}

return largest;
}

/* print all the elements in an array */
void printArray(int arr[], int arrsize) {
int arrIdx = 0;
cout << "[";
while (arrIdx < arrsize) { //example of iterating an array using while loop

if( arrIdx != (arrsize - 1) )
cout << arr[arrIdx] << ",";
else
cout << arr[arrIdx];

arrIdx++;
}
cout << "]" << endl;
}
```
page revision: 2, last edited: 06 Sep 2009 12:04