I have the following code to find first and second largest elements of an array:

using namespace std;
#include<iostream>
#include<conio.h>
#include<cstdio>
#include<string.h>

int* create(int);
int maximum(int *,int);
int second_max(int *,int);
void freememory(int*);

int main(void)
{
    int *p,size;
    cout<<"Enter size of the array:";
    cin>>size;
    p=create(size);
    cout<<"\nMaximum elemnt in the array is:"<<maximum(p,size);
    cout<<"\nSecond maximum element in the array is:"<<second_max(p,size);
    freememory(p);
    cin.get();
    return 0;
    
}

int* create(int s)
{
     int *a;
     a=new int[s];
     cout<<"Enter elements of array:";
     for(int i=0;i<s;i++)
     {
             cin>>*(a+i);
             cout<<"\n";
     }
     return a;
}

int maximum(int *a,int s)
{
    cout<<"\nFinding maximum element in array:";
    int max;
    max=a[0];
    for(int i=0;i<s;i++)
    {
       if(*(a+i)>max)
       max= *(a+i);
    }
    return max;
}

int second_max(int *a,int s)
{
    cout<<"\nFinding second maximum element in array:";
    int max,smax;
    max=a[0];
    for(int i=0;i<s;i++)
    {
       if(*(a+i)>max)
       max= *(a+i);
    }
    smax=a[0];
    for(int i=0;i<s;i++)
    {
      if((*(a+i)>=smax) && (*(a+i)!=max))
      smax=*(a+i);
    }
    return smax;
}

void freememory(int *a)
{
     cout<<"\nFreeing memory now:";
     delete []a;
}

The above code compiles fine but when executing does not produce the desired output.. Please help,,I am using dev c++ as compiler..

It works fine on gcc in linux. Try using Code::Blocks instead of Dev-C++, which is outdated and has several issues with Windows Vista/7.

Instead of creating 2 function, maximum and second maximum, just create 1 function
called sortArray. Then you can just get the maximum at element 0 or the last element,
depending if you sort it descending or ascending. You can get the
second,third,fourth... or whatever largest easy as well.

thanks for the answer,your method would certainly simplify the problem but I just want to know the bug in the above code that stops it from giving the correct output..

It worked fine for me, with correct output.

Even I got my mistake, I was missing getch() function that is not required with the gcc compiler you are using.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.