Pages

Thursday, November 19, 2015

C++ Program to Find Largest and Smallest Number in Array


 
The c++  program below generates a random number and stores it in an array, then  passes an array to a function which calculates the maximum and minimum number in the array and displays it.

Also Read: C++ Program to Find All The Roots Of A Quadratic Equation

How the program works:

  • Declare array of size 10
  • Using for loop assign array indexes with random values between 1 and thousand
  • Call the function and pass array and its size as argument
  • Function declares two integers max and min and assign both integers with arrays first index value
  • Then with in for loop there are two if condition first check is for minimum number and second check is for maximum number
  • Finally program display the output values of both integers min and max

Also Read: C++  Program For Binary Equivalent Of a Decimal Number

#include <iostream.h>
#include <stdlib.h>

void FindMaxMin(int *array, int size)
{
int min,max;
min=max=array[0];
for(int i=1;i<size;i++)
{
if(array[i]<min)
min=array[i];
else if(array[i]>max)
max=array[i];
}
cout<<"Minimum Number = "<<min<<endl;
cout<<"Maximum Number = "<<max<<endl;
}
int main()
{
int array[10];
for(int i=0;i<=9;i++)
{
array[i]=rand()%1000+1;
cout<<"array ["<<i<<"]"<<"= "<<array[i]<<endl;
}
FindMaxMin(array,10);
return 0;
}
 
Also Read: C++ Program to Check If a Number Is A Perfect Number or Not 
 
Source