C bootcamp · Lab 09

Reverse a word

mediumStrings12 minLesson: C Strings

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read one word (letters only, no spaces). Print the word reversed.

A C string ends with a null byte. Reverse the characters before that null, then print with %s.

Input. One word of at most 32 characters.

Output. The reversed word.

Constraints

  • 1 ≤ length ≤ 32
  • The word contains no spaces.

Examples

Example 1
Input
code
Output
edoc
Example 2
Input
C
Output
C
Hint
  1. scanf("%31s", word) reads a word. strlen(word) is the length.
  2. Swap word[i] with word[len - 1 - i] for i from 0 to len/2 - 1.
Show correct code

Peek only after you have tried. You can still Check your own version.

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

int main(void) {
  char word[33];
  if (scanf("%32s", word) != 1) {
    return 1;
  }
  int len = (int)strlen(word);
  for (int i = 0; i < len / 2; i++) {
    char tmp = word[i];
    word[i] = word[len - 1 - i];
    word[len - 1 - i] = tmp;
  }
  printf("%s\n", word);
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.