Tsallaka zuwa abun ciki
Justice Tech School

Practice: Reverse a String

Swap characters from both ends.

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

int main(void) {
  char s[] = "hello";
  int n = strlen(s);
  for (int i = 0; i < n / 2; i++) { char t = s[i]; s[i] = s[n - 1 - i]; s[n - 1 - i] = t; }
  printf("%s\n", s);
  return 0;
}

Result

olleh

Exercise

Last index.

s[n - ]

Quiz Test

How many swaps for length 5?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.