Tuesday, July 14, 2009

Write a program in c for strcmp without using library function with pointers?

iam serching job somany comapnies asking this question but iam not getting lz reply anybody

Write a program in c for strcmp without using library function with pointers?
/*


* myStrCmp compares two strings s1 and s2 and returns an * integer value which would be 0 if the strings are equal or else the * difference of ascii of first letter.


*/


int myStrCmp(char *s1, char *s2)


{


int diff=0;





//check for invalid input or arguments.


if(s1==NULL || s2==NULL)


{


printf("Invalid input");


exit(1);


}





while(1)


{





// if either of string ends then break the loop.


if(*s1 =='\0' || *s2=='\0')


break;





//if the character is equal then increase the pointers and continue the loop.


if(*s1 ==*s2)


{


s1++;


s2++;


continue;


}





//if they are different then subtract and break the loop


if(*s1!=*s2)


{


diff=*s1-*s2;


break;


}


//end of infinie loop


}





return diff;





}
Reply:#include%26lt;stdio.h%26gt;


#include%26lt;string.h%26gt;


main()


{


char a[30],b[30];


int n;


clrscr();


printf("enter string1 :\n");


gets(a);


printf("enter string2 :\n");


gets(b);


n=xstrcmp(a,b);


printf("the difference value=%d",n);


getch();


}





int xstrcmp(char *a,char *b)


{


while(*a==*b)


{


if(*a==NULL) //case when 2 strings


return(0); //entered are the same


a++;


b++;


}


return(*a-*b);


}


No comments:

Post a Comment