Skip to main content

Reverse a string using functions

Short answer

countChars returns the string length by counting characters until '\0'. reverse copies characters from the end of the source to the start of the destination and appends '\0'. main reads with fgets, strips the newline, and prints length and reversed string. For 'Pulchowk Campus', length=15, reverse='supmaC kwohcluP'.

Write a C program to read a string and display its reverse. Use user defined function to count number of characters in it and to reverse it.

Method.

  1. Read the string (using fgets so that spaces are accepted).
  2. countChars() returns the number of characters by counting until the null character '\0'.
  3. reverse() copies the characters from the last to the first into a second array and puts '\0' at the end.
  4. main() displays the length and the reversed string.
#include <stdio.h>

int countChars(char s[])
{
    int n = 0;
    while (s[n] != '\0')
        n++;
    return n;
}

void reverse(char s[], char r[])
{
    int n = countChars(s);
    for (int i = 0; i < n; i++)
        r[i] = s[n - 1 - i];
    r[n] = '\0';
}

int main(void)
{
    char str[100], rev[100];
    printf("Enter a string: ");
    fgets(str, sizeof str, stdin);
    for (int i = 0; str[i]; i++)            /* remove trailing newline */
        if (str[i] == '\n') str[i] = '\0';
    reverse(str, rev);
    printf("Length = %d\nReverse = %s\n", countChars(str), rev);
    return 0;
}

Sample run

Input: Pulchowk Campus

Enter a string: Length = 15
Reverse = supmaC kwohcluP

The length of "Pulchowk Campus" is 15 (the space is counted).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →