I have to print last and second last characters from a word. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I have to print last and second last characters from a word.

eg. when input is APPLE then output should be E L but i am confused with functions written after main(). please help char* lastLetters(char* word) { //what should i write here??? } int main() { FILE *f = stdout; char *output_path = getenv("OUTPUT_PATH"); if (output_path) { f = fopen(output_path, "w"); } char* res; char* word; word = (char *)malloc(512000 * sizeof(char)); scanf("\n%[^\n]",word); res = lastLetters(word); fprintf(f, "%s\n", res); fclose(f); return 0; }

29th Jan 2018, 3:51 PM
Alind
Alind - avatar
6 Answers
+ 3
i m getting no output
30th Jan 2018, 1:53 PM
Alind
Alind - avatar
+ 2
return &[(strlen(word)-2]); I m getting output as LE instead of E L
29th Jan 2018, 6:19 PM
Alind
Alind - avatar
+ 1
I tried it but it was showing some error and sometimes no output
29th Jan 2018, 5:59 PM
Alind
Alind - avatar
+ 1
Here you go. char *res = (char *) malloc(3*sizeof(char));//one extra character to store NULL char. int i, j; for(i = 0; word[i] != '\0'; i++) ; for(j =0; i>=0 && j <2; i--,j++) { res[j++] = word[--i]; } res[j] = '\0'; return res;
29th Jan 2018, 6:36 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar
0
First, using a loop you should traverse till the end of the word. Copy the last two characters from backwards into a new dynamically created array, and then return it. Try implementing this yourself. If you are unable to, I will help you.
29th Jan 2018, 5:57 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar
0
@Alind, can you show us what you tried?
29th Jan 2018, 6:14 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar