-2
int i;
char str[100];
char *p;

puts("Enter a string:");
gets(str);
system("cls");

p = &str;
    for (i = 0; i < strlen(str); i++) {
        printf("\n%s", p);
        ++p;
        //printf("\n%d %d", i, *p);
    }

    for (i=2*i+1; i > strlen(str); i--) {
        printf("%s\n", p);
        p--;
        //printf("\n%d %d", i, *p);
    }

The output of this program is

"alpine
lpine
pine
ine
ne
e
e
ne
ine
pine
lpine
alpine".

How to make it display 'e' only once, not twice?

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    You managed to write a code like that and you do not know how to ignore a character which repeats itself? – Michi Mar 06 '18 at 18:00
  • 2
    Even in throwaway example code, `gets()` is a fundamentally bad idea. – mlp Mar 06 '18 at 18:06
  • Just switch the order of the pointer decrement and the print – Omer Dagan Mar 06 '18 at 18:06
  • Please read: "[Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used)" – Deduplicator Mar 06 '18 at 19:10

2 Answers2

2

Problem with your code is that when you p reach at last character of string you are incrementing it one more time before start decrementing. So if you look carefully after first single e there is null string also printed.

Try this.

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

int main() {
   int i;
    char str[100];
    char *p;

    puts("Enter a string:");
    gets(str);

    p = &str;
    for (i = 0; i < strlen(str); i++) {
        printf("\n%s", p);
        ++p;
    }
    p--;
    for (; i > 1; i--) {
        p--;
        printf("\n%s", p);
    }
}
yajiv
  • 2,901
  • 2
  • 15
  • 25
  • 1
    Many thanks, that's an elegant solution. For some reason however, unless you re-write the second loop as "for(; i>=2; i--)" weird stuff is being printed out for the last 2 iterations. – Larry Teischwilly Mar 06 '18 at 18:19
  • yup, you are right, Thanks for pointing out that. the reason for that is we are going past to string start character, so it's printing weird stuff if I write "for(;i>=0;i--)" – yajiv Mar 06 '18 at 18:22
0
#include<stdio.h>

int main() 
{
    int i;
    char str[100];
    char *p;

    puts("Enter a string:");
    gets(str); // input word alpine, has six letters
    system("cls");

    p = &str;
    for (i = 0; i < strlen(str); i++) {
        printf("\n%s", p);
        ++p;
    } // At the end of this i equals 6

    // p is now pointing at a l p i n e \0 
    //                                   ^ here at the null terminator

    // In the following loop you set i to 13, this will loop 7 times.
    // First you print the null terminator \0 and \n
    // Then the 6 characters of alpine backwards

    for (i = 2 * i + 1; i > strlen(str); i--) 
    {
        printf("%s\n", p);
        p--;
    }
}

I'll leave it to you to figure out the solution.

Zebrafish
  • 11,682
  • 3
  • 43
  • 119