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 maximum number among it.
In the program, we input n number from the user and store it in the form of an array. Then we assign an extra variable with value 0. The extra variable is compared with all elements of the array. If any number in the array is greater than the extra variable then the greater value is assigned to the extra variable. This process is executed for all values of the array and we get the maximum number.
Program
#include<iostream.h>
#include<conio.h>
void main()
{
int a[50],n,i,max=0;
clrscr();
cout<<"How many numbers do you want to input=";
cin>>n;
cout<<endl;
if (n>50)
{
cout<<"Invalid input";
goto x;
}
for(i=1;i<=n;i++)
{
cout<<"Enter the number in a["<<i<<"]= ";
cin>>a[i];
if (a[i]>max)
max=a[i];
}
cout<<endl<<"The maximum number= "<<max;
x:getch();
}
#include<conio.h>
void main()
{
int a[50],n,i,max=0;
clrscr();
cout<<"How many numbers do you want to input=";
cin>>n;
cout<<endl;
if (n>50)
{
cout<<"Invalid input";
goto x;
}
for(i=1;i<=n;i++)
{
cout<<"Enter the number in a["<<i<<"]= ";
cin>>a[i];
if (a[i]>max)
max=a[i];
}
cout<<endl<<"The maximum number= "<<max;
x:getch();
}
Output
FINDING THE MAXIMUM NUMBER |
Explanation
In the above program, we have entered 5(i.e. n=5) numbers. The for loop is executed as follows:i(<=5) max a[i] a[i]>max Action
1 0 a[1]=67 True max=a[1]=67
2 67 a[2]=88 True max=a[2]=88
3 88 a[3]=110 True max=a[3]=110
4 110 a[4]=98 False
5 110 a[5]=52 False
In this way, the maximum value is stored in max variable and displayed on the screen.