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?
-%26gt; I'll start with the statement strrev(y).


This statement reverses string y





-%26gt; now strcpy(a,y) stores the reversed contents in char array a (tunaep).





-%26gt; Now a[1]='\0' makes the char array a={'t'} coz the second variable in the array is a null character so the string termintates there.





-%26gt; now strcat(a,"ea") appends 'ea' to the char array a. So a becomes a={'t','e','a'}





-%26gt; strcat(a,z) appeds content of char array z to to array a. So array a becomes a={'t','e','a','c','u','p'}





-%26gt; So when you print the string a you get the output as content of a , that is teacup !!
Reply:i hope the program will not compile smoothly, as the strrev(), strcpy() and strcat() functions requires to include the %26lt;string.h%26gt;





any way i am not a compiler and can explain eventhoug it has errors.





The first two lines includes the stdio.h and conio.h responsible for char datatype, printf() and getch();





Then starts the main()//[void main() can be better]





the next line declares the char array 'a' of size 20





The next line declares and initializes the array x with coconut\0 // the last char is null char.





similarly the next two lines initiates peanut and cup for y and z respectively.





strrev(y);





this reverses the string y and stores it on the variable array y, so y now becomes "tunaep\0"





strcpy(a,y);


strcpy copies a string to another,a is destination, y is source.


now a becomes "tunaep\0"





a[1]='\0'; this makes a as "t\0"





strcat(a,"ea");


This then places ea after 't' in a. so a becomes "tea\0"





strcat(a,z); as z is "cup\0", strcat combines them and a becomes "teacup\0"





printf("%s",a); // then displays the string in variable a


ie. teacup





getch() // waits for a key stroke, providing you enough time to take a look at the output.
Reply:strrev(y) %26lt;= string reverse. since peanut is in 'y' then u get tunaep inside y[10]


then you copy that into a[20]


so now 'a' = tuneap





a[1]='\0' %26lt;= puts a null character inside 'a'


so now 'a' just has the letter t


strcat(a,"ea") %26lt;= string concatenation.


basically that just adds the letters "ea" to the end of 'a'


strcat(a,z) %26lt;= same thing adds "cup" to the end


so when you put it all together, u get


teacup


No comments:

Post a Comment