C Program to Reverse a Given String

This page contains a C program that reverses a given string. The program uses basic string manipulation techniques to achieve this task.

Program Explanation

The C program to reverse a string follows these steps:

  1. Include necessary headers: Include the <stdio.h> and <string.h> headers for input/output functions and string manipulation functions.
  2. Main Function: The main function is the entry point of the program.
  3. Input String: Define a string that you want to reverse.
  4. Reverse the String: Use a loop to reverse the string by swapping characters from the start and end.
  5. Print the Result: Output the reversed string to the console.

C Program Code

/*
 * C program to reverse a given string.
 */
#include <stdio.h>
#include <string.h>

/**
 * Function to reverse a given string.
 * @param str the string to be reversed
 */
void reverseString(char* str) {
    int n = strlen(str); // Get the length of the string
    for (int i = 0; i < n / 2; i++) {
        // Swap characters from start and end
        char temp = str[i];
        str[i] = str[n - i - 1];
        str[n - i - 1] = temp;
    }
}

/**
 * Main function which is the entry point of the program.
 * @return 0 on successful execution
 */
int main() {
    // Define the string to be reversed
    char str[] = "Hello, World!";
    
    // Print the original string
    printf("Original String: %s\n", str);
    
    // Call the reverse function
    reverseString(str);
    
    // Print the reversed string
    printf("Reversed String: %s\n", str);
    
    return 0;
}

Program Details

The program contains the following:

  • reverseString Function: This function takes a string as input and reverses it in place by swapping characters from the start and end.
  • main Function: The entry point of the program where the string is defined, the reverse function is called, and the results are printed.

Running the Program

To run the program:

  1. Save the code in a file named reverse_string.c.
  2. Compile the program using the command: gcc reverse_string.c -o reverse_string.
  3. Run the compiled program using the command: ./reverse_string.

 

Explanation of the C Program:

  1. Header Inclusions: The program includes <stdio.h> for input/output functions and <string.h> for string manipulation functions.
  2. reverseString Function:
    • Takes a character array (char* str) as input.
    • Calculates the length of the string using strlen().
    • Uses a loop to swap characters from the start and end of the string until the middle of the string is reached.
  3. main Function:
    • Defines a string str to be reversed.
    • Prints the original string.
    • Calls the reverseString function to reverse the string.
    • Prints the reversed string.

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

22 thoughts on “C Program to Reverse a Given String”
  1. I do not even know how I ended up here, however I assumed this submit was once good.

    I don’t recognize who you’re however certainly you are going to a well-known blogger
    if you aren’t already. Cheers!

  2. I every time used to study piece of writing in news papers but now as I am
    a user of internet therefore from now I am using net for posts, thanks to web.

  3. First off I would like to say superb blog! I had
    a quick question that I’d like to ask if you do not
    mind. I was interested to know how you center
    yourself and clear your head prior to writing.
    I’ve had difficulty clearing my thoughts in getting my thoughts
    out there. I truly do take pleasure in writing but it just seems like
    the first 10 to 15 minutes are generally lost simply just trying to figure out how to begin. Any ideas or tips?

    Thank you!

  4. Hey would you mind stating which blog platform you’re working with?
    I’m looking to start my own blog soon but I’m having a tough time making a decision between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your design seems different then most blogs and I’m looking for something unique.

    P.S Sorry for being off-topic but I had to ask!

  5. My coder is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type on numerous websites for about a
    year and am concerned about switching to another platform.
    I have heard fantastic things about blogengine.net. Is there a way I
    can import all my wordpress posts into it? Any help would be really appreciated!

  6. I’m really loving the theme/design of your blog. Do you ever run into
    any internet browser compatibility issues?
    A couple of my blog readers have complained about my website not working correctly in Explorer but looks great in Chrome.

    Do you have any advice to help fix this problem?

  7. Thanks for another fantastic post. The place else may just anybody get that type of info
    in such a perfect manner of writing? I’ve a
    presentation subsequent week, and I am on the search for
    such information.

  8. 멋지다! 정말 멋진 기사입니다, 이 기사에서 많은 명확한 아이디어를 얻었습니다.

    I have read so many content concerning the blogger lovers however this piece of writing
    is genuinely a fastidious paragraph, keep it up.

    Wow, what an outstanding blog! Your posts on kinetic energy questions
    class 9 are spot-on. I love how you break down complex topics into easy-to-understand points.
    I’ll be sharing this with my friends. Many thanks for the
    great content!

    이 블로그를 발견한 게 행운이에요! kinetic power hk limited에 대한 글이 너무
    흥미롭고 잘 쓰여 있어요. 소셜 미디어에서
    공유했어요. 게스트 포스트로 다른 사이트와
    협업할 계획 있으신가요? 감사합니다!

  9. Hey I am so thrilled I found your blog page, I really found you by
    error, while I was browsing on Askjeeve for something else, Anyways I am here now and would just like
    to say thank you for a incredible post and a
    all round enjoyable blog (I also love the theme/design), I
    don’t have time to read through it all at the minute but I have bookmarked it and also added in your RSS feeds, so when I have time I will be
    back to read more, Please do keep up the superb work.

  10. Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
    Выяснить больше – https://vivod-iz-zapoya-1.ru/

  11. When I initially left a comment I seem to have clicked the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I
    get four emails with the same comment. Perhaps there is a way you can remove me from that service?
    Appreciate it!

Leave a Reply to sex 18+ mới nhất Cancel reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)