I this post we have provided part 2 of the C programs most commonly asked in interview along with answers. We recommend you to try to answer the questions, before referring to the given answer. If you find any mistake or a better alternate solution we are happy to see your suggestions and comments
1. Write the implementation of strcmp() function
1 2 3 4 5 6 7 8 9 10 11 12 |
int strcmp(const char *lstr, const char *rstr) { while(*lstr && *rstr) { if(*lstr != *rstr) return *lstr - *rstr; lstr++; rstr++; } if(*lstr == *rstr) return 0; return *lstr - *rstr; } |
2. Write the implementation of strncmp() function
1 2 3 4 5 6 7 8 9 10 11 12 |
int strncmp(const char *lstr, const char *rstr, size_t len) { while(*lstr && *rstr && --len) { if(*lstr != *rstr) return *lstr - *rstr; lstr++; rstr++; } if(*lstr == *rstr) return 0; return *lstr - *rstr; } |
3. Write the implementation of strstr() function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
char * strstr(char *string, const char *needle) { for(; *string; string++) { if(*string == *needle) { const char *s = string + 1; const char *n = needle + 1; while(1) { if(0 == *n) return string; if(*n++ != *s++) break; } } } return NULL; } |
4. Write a function to search a sub string from reverse
check again later
5. Write a function to convert a given string to lower case
1 2 3 4 5 6 7 8 |
char * lower(char *str) { int I; for(I = 0; str[I]; I++) if('A' <= str[I] && str[I] <= 'Z') str[I] = 'a' + str[I] - 'A'; return str; } |
6. Write a function to convert a given string to upper case
1 2 3 4 5 6 7 8 |
char * upper(char *str) { int I; for(I = 0; str[I]; I++) if('a' <= str[I] && str[I] <= 'z') str[I] = 'A' + str[I] - 'a'; return str; } |
7. Write a function to reverse a given string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
char * reverse(char *str) { char ch; char *itr = str; char *end = str; while(*end) end++; while(--end > itr) { ch = *end; *end = *itr; *itr++ = ch; } return str; } |
8. Write a function to function if a given string is palindrome
1 2 3 4 5 6 7 8 9 10 |
int ispalind(char *str) { char *itr = str; char *end = str; while(*end) end++; while(--end > itr) if(*itr++ != *end) return 0; return 1; } |
9. Write the implementation of itoa() function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
char * itoa(int num, int base, char *str) { int rem = 0; char *end = str + sizeof num * 8; *end = 0; while(num) { end--; rem = num % base; if(rem < 10) *end = '0' + rem; else *end = 'A' + rem - 10; num = num / base; } strcpy(str, end); return str; } |
10. Write a function to trim leading space
1 2 3 4 5 6 7 8 9 10 11 12 13 |
char * triml(char *str) { char *cpy = str; while(*cpy) { if('n' == *cpy || 't' == *cpy || 'r' == *cpy || ' ' == *cpy) cpy++; else break; } strcpy(str , cpy); return str; } |