Showing posts with label find second highest from array of numbers. Show all posts
Showing posts with label find second highest from array of numbers. Show all posts

Saturday, May 7, 2016

c++ program to find second max element from an array using malloc

#include<iostream.h>
class A
{
 public:
 int *a,i,j,smax,max,n;
 A();
 A(int);
 ~A();
 void input_func();
 void output_func();
 void find_smax();
};
A::A()
{
}
A::A(int n)
{
 a=new int(n);
 this->n=n;
 input_func();
}
A::~A()
{
 cout<<"\nA's destructor is called";
}
void A::input_func()
 {
  cout<<"Enter "<<n<<" nos";
  //int *k=i;
  for(i=0;i<n;i++)
   {
    cin>>*(a+i);
    //a++;
   }
  // a=k;
  output_func();
 }
void A::output_func()
 {
  cout<<"\nNumber's are";
  for(i=0;i<n;i++)
   {
    cout<<" "<<*(a+i);
   }
   find_smax();
 }
void A::find_smax()
 {
  int flag=0;
  max=*a;
  for(i=1;i<n;i++)
   {
    if(flag==0)
     {
       if(*(a+i)==*(a))
{
continue;
}
       else
{
flag=1;
if(*(a+i)>max)
 {
  smax=max;
  max=*(a+i);
 }
else
 {
  smax=*(a+i);
 }
}
     }
    else if(*(a+i)>smax)
     {
      if(*(a+i)>max)
       {
smax=max;
max=*(a+i);
       }
      else if(*(a+i)!=max)
       {
smax=*(a+i);
       }
     }
   }
   if(flag==1)
    cout<<"Smax ="<<smax;
   else
    cout<<"All numbers are equal";
 }
int main()
{
 int n;
 cout<<"\nHow many values";
 cin>>n;
 A a_object(n);
 return 0;
}
output
How many values 10
Enter 10 nos 5 8 5 0 5 4 8 4 6 2
Number's are 5 8 5 0 5 4 8 4 6 2
Smax=6