Open In App

Program to reverse a word

Last Updated : 19 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Write a program to reverse a given word.

Examples:

Input: “Hello”
Output: “olleH”

Input: “Programming”
Output: “gnimmargorP”

Approach: To solve the problem, follow the below idea:

It can be observed that we can reverse a word by traversing over the original string in reverse order and then pushing the characters from the back to a new string. Finally, return the final string.

Step-by-step algorithm:

  1. Create a variable to store the reversed word.
  2. Traverse the original word from the last character to the first.
  3. Append each character to the reversed word.

Below is the implementation of the algorithm:

C++




#include <bits/stdc++.h>;
using namespace std;
 
string reverseWord(string word) {
    string reversedWord = "";
      for(int i = word.length() - 1; i >= 0; i--) {
        reversedWord.push_back(word[i]);
    }
      return reversedWord;
}
 
int main() {
    string word = "Hello";
    cout<< "Original Word: " << word << endl;
    cout << "Reversed Word: " << reverseWord(word) << endl;
    return 0;
}


C




#include <stdio.h>
 
// Function to reverse a word and return the reversed word
char* reverseWord(const char* word)
{
    int length = strlen(word);
    // +1 for null terminator
    char* reversedWord
        = (char*)malloc((length + 1) * sizeof(char));
 
    for (int i = 0; i < length; i++) {
        reversedWord[i] = word[length - 1 - i];
    }
     
      // Null-terminate the reversed string
    reversedWord[length] = '\0';
    return reversedWord;
}
 
int main()
{
    const char* originalWord = "Hello";
    char* reversed = reverseWord(originalWord);
 
    printf("Original Word: %s\n", originalWord);
    printf("Reversed Word: %s\n", reversed);
 
    free(reversed); // Don't forget to free the allocated
                    // memory
    return 0;
}


Java




public class ReverseWord {
    // Function to reverse a word and return the reversed
    // word
    static String reverseWord(String word)
    {
        int length = word.length();
        StringBuilder reversedWord
            = new StringBuilder(length);
 
        for (int i = length - 1; i >= 0; i--) {
            reversedWord.append(word.charAt(i));
        }
 
        return reversedWord.toString();
    }
 
    public static void main(String[] args)
    {
        String originalWord = "Hello";
        String reversed = reverseWord(originalWord);
 
        System.out.println("Original Word: "
                           + originalWord);
        System.out.println("Reversed Word: " + reversed);
    }
}


Python3




def reverse_word(word):
    return word[::-1]
 
 
def main():
    original_word = "Hello"
    reversed_word = reverse_word(original_word)
 
    print("Original Word:", original_word)
    print("Reversed Word:", reversed_word)
 
 
if __name__ == "__main__":
    main()


C#




using System;
 
class Program {
    // Function to reverse a word and return the reversed
    // word
    static string ReverseWord(string word)
    {
        char[] charArray = word.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
 
    static void Main()
    {
        string originalWord = "Hello";
        string reversedWord = ReverseWord(originalWord);
 
        Console.WriteLine("Original Word: " + originalWord);
        Console.WriteLine("Reversed Word: " + reversedWord);
    }
}


Javascript




function reverseWord(word) {
    return word.split('').reverse().join('');
}
 
function main() {
    const originalWord = "Hello";
    const reversedWord = reverseWord(originalWord);
 
    console.log("Original Word:", originalWord);
    console.log("Reversed Word:", reversedWord);
}
 
main();


Output

Original Word: Hello
Reversed Word: olleH

Time Complexity: O(N) where N is the length of the word.
Auxiliary Space: O(N)



Similar Reads

Program to count the number of consonants in a word
Write a program to count the number of consonants in a given word. Consonants are the letters of the English alphabet excluding vowels ('a', 'e', 'i', 'o', 'u'). Examples: Input: "programming"Output: 8 Explanation: The eight consonants are: 'p', 'r', 'g', 'r', 'm', 'm', 'n', 'g') Input: "hello"Output: 3 Explanation: There are three consonants: 'h',
5 min read
Program to count the number of characters in a word
Write a program to count the number of characters in a word. Examples: Input: Word: "programming"Output: 11 Input: Word: "hello"Output: 5 Approach: To solve the problem, follow the below idea: To count the number of characters in a word, maintain a variable to count all the characters. Iterate through each character in the word and increment the co
2 min read
Program to count the number of vowels in a word
Write a program to count the number of vowels in a given word. Vowels include 'a', 'e', 'i', 'o', and 'u' (both uppercase and lowercase). The program should output the count of vowels in the word. Examples: Input: "programming"Output: 3Explanation: The word "programming" has three vowels ('o', 'a', 'i'). Input: "HELLO"Output: 2Explanation: The word
3 min read
Program to reverse order of words in a sentence
Write a program to reverse the order of words in a given sentence. A word is defined as a sequence of non-space characters. The sentence is a collection of words separated by spaces. Examples: Input: "Hello World"Output: "World Hello" Input: "Programming is fun"Output: "fun is Programming" Approach: To solve the problem, follow the below idea: The
3 min read
Program to reverse a sentence
Write a program to reverse a sentence. Examples: Input: "Practice with GFG" Output: "GFG htiw ecitcarP" Input: "Programming is fun" Output: "nuf si gnimmargorP" Approach: To solve the problem, follow the below idea: It can be observed that we can reverse a sentence by traversing over the original sentence in reverse order and then pushing the chara
2 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
Program to Print the Trapezium Pattern
Given 'num' which indicates number of lines.The task is to print a trapezium pattern in num lines.Examples: Input : 4 Output : 1*2*3*4*17*18*19*20 5*6*7*14*15*16 8*9*12*13 10*11 Input : 2 Output : 1*2*5*6 3*4 Algorithm : step 1. To read num which indicates the number of lines. step 2.We are diving the pattern into 2 halves that is LHS part and the
6 min read
Recursive program to print triangular patterns
We have discussed iterative pattern printing in previous post. Examples: Input : 7 Output : * * * * * * * * * * * * * * * * * * * * * * * * * * * * Algorithm:- step 1:- first think for the base condition i.e. number less than 0 step 2:-do the recursive calls till number less than 0 i.e:- printPartten(n-1, k+1); step 3:-print the spaces step 4:-then
8 min read
Program to print Hut
Given a number N, the task is to print Hut of width n. [caption width="800"]Output[/caption] Algorithm: Take input for the width of the hut (n).If n is even, increment it by 1.Loop through rows from 0 to n - n/3.Loop through columns from 0 to n.Determine the character to print based on the position of the row and column: a. If the position is on th
9 min read
Program for Morse Code Translator (Conversion of Morse Code to English Text)
Design a Morse Code Translator that converts Morse code into English text. The Morse code consists of dots (.) and dashes (-) representing letters and numbers. Spaces(' ') separate letters, and forward slash('/') separate words. Implement a program to perform this translation. Examples:Input: Morse Code: "... --- ..."Output: English Text: "SOS"Expl
7 min read
Article Tags :