Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   help wid a program (http://www.go4expert.com/forums/help-wid-program-t21480/)

lionaneesh 24Mar2010 12:30

help wid a program
 
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)?

bluecoder 24Mar2010 13:26

Re: help wid a program
 
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 .

xpi0t0s 25Mar2010 14:37

Re: help wid a program
 
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.


All times are GMT +5.5. The time now is 07:10.