1

this is my source code for printing each word in string backwards. but this code is just printing the 1st word backward and not the entire string. after printing 1st word backward it generates a pattern of 1st and 2nd words printed backwards. If while is used instead of if then it generates an infinite loop.

// Print an Entered String Backwards
#include <stdio.h>
#include <string.h>

int main()
{
    int j,i;
    char str[100];
    printf("Enter String\n");
    gets(str);
    printf("\nString in Reverse Order\n");
    i=0;
    while(str[i]!='\0')
    {
        if(str[i]==' ')
        {
            for(j=i-1;j>=0;j--)         //Loop starts from last char and decrements upto 0th char
                printf("%c",str[j]);
            printf(" ");
        }
        i++;
    }
}
WhozCraig
  • 65,258
  • 11
  • 75
  • 141
Bob
  • 21
  • 1
  • 1
  • 6
  • SOrt out the indetation. BTW - Are these lecturers getting better at the problems they are setting students. @userX - Learn to use the debugger – Ed Heal Apr 19 '14 at 10:15
  • Your logic is wrong. Frame the logic using pen and paper, test it manually, then write the program. – 0xF1 Apr 19 '14 at 10:22
  • @user3551403 - WhozCraig (thanks) fixed it for you – Ed Heal Apr 19 '14 at 10:28
  • I dont get the description... If an input is 'bar dog' what output do you want: 'dog bar' or 'rab god' or may be 'god rab'...? – CiaPan Apr 19 '14 at 10:33
  • @CiaPan I just want to reverse d alphabets of words but retain the order of words. output of 'bar dog' should be 'rab god' – Bob Apr 19 '14 at 10:59

5 Answers5

2

Do not use gets. It's not safe and is deprecated. Use fgets instead to read an input string stdin. Now, to print each word in the string backwards, you need to change your while loop.

#include <stdio.h>

int main(void)
{
    int i, j;
    char str[100];
    printf("Enter String\n");

    // fgets reads one less than sizeof(str), i.e., 99
    // characters from stdin and stores them in str array.
    // it returns when a newline is input which it stores in
    // the the array and then appends a terminating null byte
    // to mark the end of the string
    fgets(str, sizeof str, stdin);
    printf("\nString in Reverse Order\n");

    i = 0;
    while(str[i] != '\0')
    {
        if(str[i] == ' ' || str[i] == '\n')
        {   
            // the loop condition checks for either the 
            // start of the string or a whitespace since
            // since these two cases demarcate a word from
            // other words in the string
            for(j = i - 1; j >= 0 && str[j] != ' '; j--)
                printf("%c", str[j]);

            printf(" ");    
        }
        i++;
    }
    // output a newline to flush the output
    printf("\n"); 
    return 0;   
}
ajay
  • 9,402
  • 8
  • 44
  • 71
  • `gets` is unsafe and not advisable because if the input string is too long, then it would overrun the buffer causing undefined behaviour and most likely program crash due to segfault. – ajay Apr 19 '14 at 10:59
  • @user3551403 however, if the input string is small enough to be stored in the array `str`, then `gets` would work but you should not do this. – ajay Apr 19 '14 at 11:00
0

The loop you commented shouldn't end on the 0th char, but should go upto the last white space( if there was one ).

//Print an Entered String Backwards
#include<stdio.h>
#include<string.h>

int main()
{
    int j,i; int lastWhiteSpace = 0; //there were no white spaces
    char str[100];

    printf("Enter String\n");

    gets(str);

    printf("\nString in Reverse Order\n");

    i=0;
    while(str[i]!='\0')
    {
        if(str[i]==' ')
        {
            for(j=i-1;j>=lastWhiteSpace;j--)  //Loop starts from last char and decrements upto the character after the last white space 
                printf("%c",str[j]);
            printf(" ");
            lastWhiteSpace = i + 1; //the character after this white space 
        }
        i++;
    }

    //later edit
    for(j=i-1;j>=lastWhiteSpace;j--)
        printf("%c",str[j]);
    printf("\n");
}
Valdrinium
  • 1,398
  • 1
  • 13
  • 28
  • so what should be the limiting condition 4 loop? – Bob Apr 19 '14 at 10:18
  • You should also initialize `lastWhitespace` before loop. What if sentence starts with lots of whitespaces. – 0xF1 Apr 19 '14 at 10:24
  • @Scooby this code is working only upto few words and not all the words in string. – Bob Apr 19 '14 at 10:27
  • Because you only have 100 chars in the string? It should not work for the last word only, because it needs to be treated separately. – Valdrinium Apr 19 '14 at 10:30
  • why the last word needs to be treated seperately? – Bob Apr 19 '14 at 10:57
  • Because you reach the end of the string and there are nu move spaces and the last word does't get the chance to be printed. An alternative easier solution would be to add another space in the string, before the \0 character. The code is working just fine with gets too. – Valdrinium Apr 19 '14 at 11:07
0

Every time you are testing the inner loop to zero, which will print till the start of the string each time. You need to just test till last space found. Something like this for inner loop

int lastSpace = 0, i = 0, j = 0;
while(str[i] != '\0')
{
if(str[i] == ' ')
{
for(j = i-i; j>= lastSpace; j++)
{
   printf("%c", str[j]);
}
lastSpace = i;
}
i++;
}
praks411
  • 1,972
  • 16
  • 23
  • this starts with `j=i-i == 0`. So it starts with the first character and keeps going down the other direction into some sort of heap space. This one is going to be interesting :) – ssm Apr 19 '14 at 11:06
  • @ssm but it isn't generating the output I want! :) – Bob Apr 19 '14 at 11:11
  • Just convert `j=i-i` to `j=i` :) – ssm Apr 19 '14 at 11:56
0

No need to double loop you can do in single loop.

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

int main()
{
    int j,i, len;
    char str[100];
    clrscr();
    printf("Enter String\n");
    gets(str);
    printf("\nString in Reverse Order\n");
    i = strlen(str) - 1;
    while(i > -1)
    {
    printf("%c",str[i--]);
    }
}
Pawan Chaurasiya
  • 881
  • 2
  • 16
  • 30
0
#include<stdio.h>
#include<string.h>

int main()
{
    int j,i, len;
    char str[100];
    char temp[20];
    clrscr();
    printf("Enter String\n");
    gets(str);
    printf("\nString in Reverse Order\n");
    i = 0;
    len = 0;
    j = 0;
    while(str[i] != '\0')
    {
        if(str[i] != ' ')
            temp[j++] = str[i];

        if(str[i] == ' ')
        {
            temp[j] = '\0';
            len = strlen(temp);

            while(len > -1)
            {
                printf("%c", temp[len--]);
            }
            printf(" ");
            len = 0;
            j = 0;
        }
    i++;
    }
    temp[j] = '\0';
    len = strlen(temp);
    printf(" ");
    while(len > -1)
    {
        printf("%c",temp[len--]);
    }
}
Pawan Chaurasiya
  • 881
  • 2
  • 16
  • 30