Thursday 4 October 2018

Finding out the minimum number among an array of n numbers in C++

Static and dynamic data structure


A data structure whose size cannot be changed at the run-time is called static data structure. The size of a static data structure can neither be increased nor decreased at run-time. It may lead to the wastage or shortage of memory locations.

An array is an example of a static data structure. Once the size of an array is declared it can't be changed. If we declare an array of size 5 then we can't increase or decrease its size during run-time. If we utilize only 2 locations then the remaining memory is wasted. This problem is addressed by the introduction of the dynamic data structure.

A data structure whose size can be changed at the run-time is called dynamic data structure. The size of a dynamic data structure can either be increased or decreased at run-time. It prevents the wastage or shortage of memory locations.


Write a program in C++ to input an array of numbers and find the minimum number among it.


In the program, we input n numbers from the user and store it in the form of an array. Then we assign the value of the first element of an array to an extra variable. The extra variable is compared with all elements of the array starting from the second element. If any number in the array is smaller than the extra variable then the smaller value is assigned to the extra variable. This process is executed for all values of the array and we get the minimum number.


Program


#include<iostream.h>
#include<conio.h>
void main()
{
int m[20],a,min,i;
clrscr();
cout<<"How many numbers do you want to enter=";
cin>>a;
cout<<endl;
if(a>20)
{
cout<<"Invalid size";
goto x;
}
for(i=1;i<=a;i++)
{
cout<<"Enter number m["<<i<<"]= ";
cin>>m[i];
}
min=m[1];
cout<<endl;
for(i=2;i<=a;i++)
{
if(min>m[i])
min=m[i];
}
cout<<"The minimum number= "<<min;
x:getch();
}


Output


Program to print the minimum number
FINDING THE MINIMUM NUMBER













Explanation 

 

In the above program, we have entered 5(i.e. a=5) numbers. The first value of array (a[1]) is assigned to min(i.e. min=a[1]=103). The comparison process within the for loop is executed as follows:

i(<=5)          min          m[i]                  m[i]<min          Action              
2                 103           m[2]=56           True                  min=a[2]=56
3                 56             m[3]=44           True                  min=a[3]=44
4                 44             m[4]=87           False         
5                 44             m[5]=95           False 


In this way, the minimum value is stored in the min variable and displayed on the screen.







No comments:

Post a Comment