Computer Science‎ > ‎

C Program to Reverse A String


C Program : Source code to reverse a string


/*The following program reverses a string of length below 20 characters entered by the user*/
#include<stdio.h>
#include<string.h>
int main()
{
    char word[21];
    char *temp;//This will be our temporary array to store the string while being reversed
    int ctr;
    printf("Enter the word to reverse(Length of the word must be below 20)\n");
    scanf("%s",word);
    int length=strlen(word);//strlen function returns the length of the string. Here it returns length of the string stored in word.
    temp=(char*)malloc(length*sizeof(char));//We create a temprary array of required length
    for(ctr=0;ctr<length;ctr++)
    temp[ctr]=word[length-ctr-1];
    temp[length]='\0';//We terminate the string with null character as it is required that a string should end with null character
    printf("The reversed string is %s\n",temp);
    free(temp);//free the memory
    getch();
}
/*A sample run of the program was done and output was:-
Enter the word to reverse(Length of the word must be below 20)
rabbit
The reversed string is tibbar
*/

Other Programs which you might find useful:


C Program to Reverse A String

C Program: Building an Expression Evaluator
C Program: Check for Armstrong Numbers
C Program: Check whether a string is a Palindrome or not
C Program: Common Operations on Sets - Union, Intersection, Difference, Cardinal Product
C Program: Computing exp(x), sin(x), cos(x), tan(x) using series expansions
C Program: Computing the Area of a Circle
C Program: Computing the Upper Triangular Matrix and Lower Triangular Matrix
C Program: Demonstrating File Handling Functions
C Program: Demonstrating Operations on Matrices - Addition, Subtraction, Multiplication, Inversion, Finding Determinants
C Program: Demonstrating the use of Bitwise Operators
C Program: Displaying a Histogram of word frequencies (unigram)
C Program: Distance Vector Routing Algorithm using Bellman Ford's Algorithm
C Program: Numerical Computing - The Gaussian Elimination Method
C Program: Numerical Computing - Implementing the Newton Raphson Method
C Program: Numerical Computing - the Bisection Method
C Program: Numerical Computing - The Gaussian Elimination Technique from Linear Algebra
C Program: Numerical Computing - the Jacobi Method
C Program: Printing the Pascal Triangle
C Program: Reversing the order of words in a sentence
C Program: Solving Simultaneous Equations in Two Variables
C Program: Source Code for computing the GCD(HFC) of two numbers
C Program: Source Code for Solving Quadratic Equations
C Program: Source code to solve the Josephus Problem
C Program: Sudoku Solver
C Program: The Usage of Command Line Arguments
C Program: Using the Sieve of Eratosthenes to print Prime Numbers