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

int main(int args, char *argv[]) {
    int i = 0;
    for (i = 0; i < args; i++)
        printf("\n%s", argv[i]);
    return 0;
}

As of now this program prints out whatever is written on the command line. How would I make it do this in reverse? For example, if I input "dog" it should say "god".

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70

3 Answers3

2

Try the following code:

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

int main(int argc, char *argv[]) {
    int i = 0;
    for (i = 1; i < argc; i++)
    {
        char *tmp = argv[i];
        int len = strlen(argv[i]);
        for(int j = len-1; j > -1; --j)
            printf("%c",tmp[j]);
        printf("\n");
    }
    return 0;
}
Ren
  • 2,852
  • 2
  • 23
  • 45
1

I'd break this down into two smaller tasks.

  1. Write a helper function that, given a string, prints it out in reverse order. To do so, you could use a loop that starts at the end of the string and prints each character one after the other, moving in reverse across the array as you go.

  2. Call that helper function in main inside the loop to print each string in the argv array.

Since this looks like a homework assignment, I'll leave it at this. If you're having trouble with step (1), then you may need to review how to do string processing a bit before jumping into this problem.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
1

IDEOne Link

int main(int argc, char *argv[]) {
    for (int i = 0; i < argc; ++i)
    {
        for(char* c = &argv[i][strlen(argv[i])-1]; c >= argv[i]; putchar(*c--)) ;
        putchar(' ');
    }
    return 0;
}
abelenky
  • 63,815
  • 23
  • 109
  • 159