Tuesday, July 28, 2009

Turbo C programme?

The output of this programme is teacup.Can you explain me step by step.Thanks.








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


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


main()


{


char a[20];


char x[10]="coconut";


char y[10]="peanut";


char z[10]="cup";


strrev(y);


strcpy(a,y);


a[1]='\0';


strcat(a,"ea");


strcat(a,z);


printf("%s",a);


getch();


}

Turbo C programme?
char a[20];


char x[10]="coconut";


char y[10]="peanut";


char z[10]="cup";





strrev(y); /* y = "tunaep" reverse y */


strcpy(a,y); /* a = "tunaep" copy y into a */


a[1]='\0'; /* a = "t" \0 signals end of string. a[0] = 't' */


strcat(a,"ea"); /* a = "tea" add "ea" to end of a*/


strcat(a,z); /* a = "teacup" add "cup" to end of a */


printf("%s",a);
Reply:In C the string handling functions use the character '\0' to mark the end of a string. This is called a null.





The program creates 3 arrays of characters. x contains "coconut", y contains "peanut" and z contains "cup", each of these has a '\0' at the end. a starts off empty.





The strrev(y) reverses the contents of y so it becomes "tuneap", then the strycpy copies this to a.





In C the first entry of an array is 0. Setting a[1] to '\0' means the string functions will treat it as a single character string so it is now "t". The "neap" is still stored in memory but the C string functions will ignore this.





The strcat(a,"ea") adds "ea" to the end of a so it becomes "tea".





the strcat(a,z) adds "cup" to the end of a so it is now "teacup"





The last 2 lines just display the contents of a and wait for a keypress.


No comments:

Post a Comment