Corey
Corey

Reputation: 73

How to print an entered string backwards in C using only a for loop

I want to print a string backwards. But my code seems to count down the alphabet from the last letter in the array to the first letter in the array instead of counting down the array itself and spitting out each letter in the array.

My code,

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

   int main(void) {

char word[50];
char end;
char x;

printf("Enter a word and I'll give it to you backwards: ");

scanf("%s", word);

end = strlen(word) - 1;

for (x = word[end]; x >= word[0]; x--) {
    printf("%c", x);
}

return 0;
}

Any suggestions? Thank you.

Upvotes: 1

Views: 35996

Answers (6)

Marin Alexandru
Marin Alexandru

Reputation: 1

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

/*
 * 
 */
int main(int argc, char** argv) {
    int i;
    char letters[3]="";
    printf("Enter three letters!");
    scanf("%s",letters);
    for(i=3;i>=0;i--){
        printf("%c", letters[i]);
    }
    return (EXIT_SUCCESS);
}

Upvotes: 0

Patrick Gombert
Patrick Gombert

Reputation: 53

You're calling array values and not the specific index.

for(x = end; x >= 0; x--) { printf("%c", word[x]); }

Upvotes: 4

venom
venom

Reputation: 1

//Change end to int type and modify your for loop as shown.
#include <stdio.h>
#include <string.h>

int main(void) 
{

char word[50];
int end;
char x;

printf("Enter a word and I'll give it to you backwards: ");

scanf("%s", word);

end = strlen(word) - 1;

 for (x = end; x >= 0; x--) 
 printf("%c",word[x] );


return 0;
}

Upvotes: 0

ysap
ysap

Reputation: 8115

In your loop, x is the index into the character array comprising word. So x should change from end to 0, and referencing the array should be as word[x].

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 73011

What you have loops between the array element values. You want to loop between the array indexes. Update your loop to the following:

for (x = end; x >= 0; --x) {
    printf("%c", word[x]);
}

Note that this goes from the last index to zero and output the character at that index. Also a micro-optimization in the for loop using pre-decrement.

Upvotes: 8

Anon.
Anon.

Reputation: 59993

You want to print word[x] (the xth character in the array) instead of x (the xth character in the character set).

You also want to be counting down indexes, not characters.

for(x=end, x >= 0; x--)
    printf("%c", word[x]);

Upvotes: 1

Related Questions