WAP having a function which takes an integer array as argument and returns smallest and biggest of given numbers.

Coding Problem

WAP having a function which takes an integer array as argument and returns smallest and biggest of given numbers.
 
Note: Such problem can be solved using different ways

Solution 1: Using structures

struct result
{
    int smallest,biggest;   
};
struct result smallbig(int ar[],int n)
{
    struct result r;
    int s,b,i;
    s=b=ar[0];
    for(i=1;i<n;i++)
    {
        if(ar[i]>b) b=ar[i];
        if(ar[i]<s)s=ar[i];
    }
    r.biggest=b;
    r.smallest=s;
    return r;
}
main()
{
    int ar[]={8,12,44,566,2,4565,6};
    struct result r=smallbig(ar,7);
    printf("Smallest is %d Biggest is %d",r.smallest,r.biggest);
}

Output
Smallest is 2 Biggest is 4565

Solution 2: Using call by address

void smallbig(int ar[],int n,int *smallest,int *biggest)
{
    int s,b,i;
    s=b=ar[0];
    for(i=1;i<n;i++)
    {
        if(ar[i]>b) b=ar[i];
        if(ar[i]<s)s=ar[i];
    }
    *biggest=b;
    *smallest=s;
}
main()
{
    int ar[]={8,12,44,566,2,4565,6};
    int s,m;
    smallbig(ar,7,&s,&m); //passing address
    printf("Smallest is %d Biggest is %d",s,m);
}

Output
Smallest is 2 Biggest is 4565


Comments

Popular posts from this blog

What is template?

Can we access private members of an instance?

What are wrapper classes in Java?