More Code Puzzles

1. Find Second Maximum in an array.

void findSecondMax(int a[])
{
    int max=a[0], secondmax=0;
    int size = sizeof(a)/sizeof(int);//doesnt work here
    for (int i=1;i<10;i++)
    {
        if (max < a[i])
        {    secondmax = max;
            max = a[i];
        }
        else
            if(secondmax<a[i])
            {
                secondmax = a[i];
            }
    }
    printf("second max is %d... max is %d",secondmax,max);

}

2. Remove the duplicates from an array.

void removeDuplicates()
{
    //int a[10]={1,1,1,3,3,5,5,6,6,6};
    int a[10]={1,2,2,3,4,5,5,6,7,8};
    int b[10];
    int size = 10;
    for(int i=0, j=1;j<size;j++) { if(a[i]==a[j])
        {
            for (int k=j;k<size-1;k++)
                a[k] = a[k+1];
            size--;
            j--;
        }
        else
        {
            i++;
        }
    }
    for (int j=0;j<size;j++)
    {
        printf("%d ", a[j]);
    }
}

0 comments: