• September 23, 2021

PHSARIT

Bring Technology Ideas with you

 How to find smallest and largest number in an array

As the previous post What is an array?, we have demonstrated how to declare and access array elements. Therefore this tutorials will show you how to find the smallest and largest number in array elements.

First we need to declare and access array then we start comparing the value one by one to get the lowest value elements in array as the demonstration below:

include<iostream>
using namespace std;
int main()
{
	//set user to input the number of the array in the limitation
	int n;
	cout << "Enter amount of no more than 100 elements to store:";
	cin >> n;
	int arr[100];
	// all users to enter the elements
	for (int i = 0; i < n; i++)
	{
		cout << "Element:" << i + 1 << ":" << endl;
		cin >> arr[i];
	}
	// print all elements
	cout << endl;
	cout << "You have enter all element:";
	for(int i=0;i<n;i++){
		cout << arr[i];
	}
	cout << endl;
	//find smallest and largest numbers in array
	int min = arr[0]; //first element of user input to compare all element which were entering by user to find smallest number
	int max = arr[0]; // first element of user input to compare all element which were entering by user to find largest number
	int ComValue = 0;
	//accessing to elements from index 0 to compare from index 1 to all
	for (int i=1; i < n; i++)
	{
		ComValue = arr[i];
		if (ComValue > max) //compare the largest from index 0 to the rest
		{
			max = ComValue;
		}
		if (ComValue < min) //compare the largest from index 0 to the rest
		{
			min = ComValue;
		}
	}
	cout << "Larget number is:" << max<<endl;
	cout << "Smallest number is:" << min<<endl;
system("pause > 0");
}

Result from the compiling:

    The next tutorial will show you how to sort array element from ascending ( order from smallest to largest) and the descending ( from largest to smallest)

    ——————————————————————————————————————–

    Related post