Find the smallest and largest numbers in an array

## Find the smallest and largest numbers in an array

• Understand how to break a program into functions and how every function should do only one thing
• Understand how to call functions from main()
• Understand how to use arrays in C++
```/* 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: 0, last edited: 07 Sep 2009 05:16