Code: #include<stdio.h> #include<string.h> void reverse(char str[]); int main() { char str[100]; int i; printf("Enter to reverse : "); scanf("%[^\n]",str); reverse(str); return(0); } /* Function */ void reverse(char str[]) { int i; for(i=(strlen(str));i > 0; i--) { printf("%c",str[i]); } putchar('\n'); } in this programme when we input 123 output = 32 /* non - desired result 1 missing */ input = sonal , output = lano /* s missing*/ input = aneesh ,output = hseen /*a missing */ Code: #include<stdio.h> #include<string.h> void reverse(char str[]); int main() { char str[100]; int i; printf("Enter to reverse : "); scanf("%[^\n]",str); reverse(str); return(0); } /* Function */ void reverse(char str[]) { int i; for(i=(strlen(str));i >=0; i--) { printf("%c",str[i]); } putchar('\n'); } in this program wen we input 123 the output is 231... and:- input = aneesh ,output = hseen but by my understanding this for loop is wrong.. NOW the questions:- 1. Why in the first program the output in the case "123" is "32" and in case "aneesh" output is "hseen" ? 2. Why the second program provides right results despite the loop is wrong(by my understanding)?
NOW the questions:- 1. Why in the first program the output in the case "123" is "32" and in case "aneesh" output is "hseen" ? 2. Why the second program provides right results despite the loop is wrong(by my understanding)?[/quote] The answer to the first question is that the array starts with zero so you have to compare it with zero so this for loop will be wrong for(i=(strlen(str));i > 0; i--) Where as the second for loop for(i=(strlen(str));i >=0; i--) is right as it takes zero into consideration .
Still wrong. i needs to start out as strlen(str)-1. For the input "123", '1' is at element zero, '2' is at element one, and '3' is at element ***TWO***. The terminating NULL is at element 3 and usually you do not want to consider that. No idea why you get "231..." and "hseen" as output to the 2nd program. Tried it in Visual Studio 2008 and the output was " 321" and " hseena" (because VS2008 displays NULLs as spaces). Maybe you have a compiler bug, or perhaps you get odd behaviour when your compiler tries to display a NULL. Solution is not to include the NULL in the loop and just loop over the data you want.