0

I want this code to print each word backwards, but is not printing the last word, I guess I'm missing something very basic here.

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

int main()
{
    int l;
    printf("lenght: ");
    scanf("%i",&l);
    char str[l][100];
    int lenght[l];

    for(int i=0; i<l; i++)
    {
        printf("%i : ",i);
        scanf("%s",str[i]);
        lenght[i] = strlen(str[i]);
    }

    for(int i=l-1; i>0; i--)
    {
        for(int j=lenght[i-1]; j>=0; j--)
        {
            printf("%c",str[i][j]);
        }
        printf("\n");
    }



   return 0; 
}     
2
  • You need to usei >= 0 in this for loop: for(int i=l-1; i>=0; i--) Commented Feb 23, 2020 at 13:03
  • Or, for(int i=l; i-- >0;) for the outer loop, and for(int j=lenght[i]; j-- >0;) for the inner. Commented Feb 23, 2020 at 13:09

2 Answers 2

1

i > 0 and lenght[i - 1] are causing the problem. Also consider using putchar to print a single char and size_t to represent size of a string:

for (size_t i = l; i--;) {
  for (size_t j = lenght[i]; j--;) {
    putchar(str[i][j]);
  }
  putchar('\n');
}
Sign up to request clarification or add additional context in comments.

2 Comments

why did you changed your answer, the other one worked perfectly fine, there's any difference ?
@user29893 Either way is fine. This way seems more clear to me (no need for the magic number -1)
1

This is the problem for(int i=l-1; i>0; i--).Currently the 0 index string is never processed. Set condition to i >= 0 to include 0 also.

The inner loop initialization also need to be changed to j = lenght[i] - 1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.