-3

I tried this code but at the for loop it seems to do nothing.

#include <stdio.h>
#include <stdlib.h>

void main()
{

    char word[100];
    char suf [100];
    int i,j,k = 0;
    char a [100];

    printf("Enter the word: \n");
    gets(word);
    printf("\n");



    for (i = strlen(word); i < 0; i--)
            {
                 a[i] = word[i];
                 printf("%s",a);

            }
}

Example Output:

>> Enter the word: Program

>> m

>> am

>> ram

>> gram

>> ogram

>> rogram

Community
  • 1
  • 1
  • 1
    Please read Someone answered my question! What to do now? http://stackoverflow.com/help/someone-answers , and consider accepting one of the answers to your questions – OneMoreError Aug 05 '14 at 15:27

2 Answers2

1

Using pointer arithmetic would probably be the easiest way to do this; you won't even need a temporary buffer:

for (i = strlen(word) - 1; i > 0; --i) {
    printf("%s\n", word + i);
}
cdhowie
  • 158,093
  • 24
  • 286
  • 300
1

ALTERNATIVE : Use a pointer approach :

#include <stdio.h>
#include<string.h>

int main(int argc, const char * argv[])
{
    char word[100];

    printf("Enter the word: \n");
    gets(word);
    printf("\n");
    char *ptr;
    int len = (int)strlen(word) ;

    for (int i = len -1; i > 0; --i)
    {
        ptr = &word[i];
        printf("%s\n",ptr);

    }
    return 0;
}

Explanation :

Say the string you entered is program Now, the index ranges from 0 to 6 here, and not 7. In your code, you are starting with i = strlen(word) which is wrong. You should start with i = strlen(word) -1.

Also, you should decrement till the value of i is greater than 0 - not less as in your case i < 0.

SUGGESTIONS :

Do not use void main(……). Use int main(…). The former may not be supported on all compliers.

OneMoreError
  • 7,518
  • 20
  • 73
  • 112