Saturday, May 22, 2010

Please write a c function to reverse a string , any one help me ?

I'll assume that you really want to learn from the assignment you are given, rather than just have someone give the answer to you outright.





To reverse a string, you need to first exchange the first and last characters in the string. So, figure out the index of the last character in the string, and this will be easy. You'll need to calculate the length of the string to do this.





With this done, you can continue the process by exchanging the second and next-to-last character of the string. In fact, you can write a loop to perform the appropriate exchanges until you are finished.





Figuring out the terminating condition of the loop requires a little thought, and you should consider the two cases of strings of odd and even length. Drawing a picture may help here.





Ultimately, this problem can be solved by breaking it into smaller problems, each of which can be solved with a little thought. This is what your instructor hopes you will do. Developing these problem solving skills is what will make you a valuable employee.

Please write a c function to reverse a string , any one help me ?
#include %26lt;string.h%26gt;


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


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











int main() {





char s[1000];


int i;


int len=0;





while (1) {





printf("\n\n\tEnter a string : ");


gets(s);





printf("\n");





for(i=0;s[i];i++) {


printf("%c",s[i]);


}


len=strlen(s);


printf("\n\n");


for(i=len-1; s[i], i%26gt;=0; i--)


printf("%c",s[i]);


}


return 0;


}
Reply:Hi, i dont remember exactly , but i can give u the steps, u have to try urself:


if the number is x,


then first take the remainder of this number dividing by 10, which will give you te last diggit of this number, get it printed,


then find the integer value of it while dividing by 10.


then repeat the above steps on this number.





example:


if number x = 123,


dividing by 10, will give the remainder as 3., so save ths number.


now dividing by 10 and finding the ointeger value, it will be 12,


again repeating the above step,


divide this number by 10 for finding remainder, which will be 2,again save ths number


and diving by 10 for finding integer value, u will get 1, which is the last digit, so save this also, now if u print in sequence, the saved numbers, u will get:


321,which is the reverse of the number x.
Reply:Do your homework! Hint... stack.


No comments:

Post a Comment