Thursday 6 June 2019

Finding second largest in a string of numbers

#include <stdio.h>
#include <limits.h>

main()
{
char st[100];
printf("\nEnter a string\n");
scanf("%s",st);
int i,first,second;
first = second =INT_MIN;
for(i=0;st[i]!='\0';i++)
{
if(st[i]-'0' > first)
{
second = first;
first=st[i]-'0';
}
else if(st[i]-'0' > second && st[i]-'0' != first)
second=st[i]-'0';
}
if(second == INT_MIN)
printf("there is no second minimum");
else
printf("second min = %d",second);
}

=========================Using sorting=========================


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int co(const void *p, const void *q)
{
   return *(char *)p-*(char *)q;
}
main()
{
char st[100];
printf("\nEnter a string\n");
int i,max=0,l=strlen(st);
qsort(st,l,sizeof(char),co); // for sorting characters in string
max=st[l-1]-'0';
for(i=l-2;i>=0;i--)
{
if(max != st[i]-'0'){

printf("%d",st[i]-'0');
break;
}
}
}

==============================================================

No comments:

Post a Comment