Write a Program to reverse a string

27 June 2022

write-a-program-to-reverse-a-string


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

Get an input string from user and print it in reverse order.

 

Input

Hello

Output

olleH

 

C Program

#include<stdio.h>

#include<string.h>

int main()

{

    char str1[50]={0};

    char str2[50]={0};

    printf("Enter a string: ");

    fgets(str1,sizeof(str1),stdin);

    int n=strlen(str1)-1;

    for(int i=0;i<=n;i++)

    {

        str2[i]=str1[n-i];

    }

    printf("Reverse string: %s",str2);

    return 0;

}

 

 

C++ Program

#include<iostream>

#include<string.h>

using namespace std;

int main()

{

    char str1[50]={0};

    char str2[50]={0};

    cout<<"Enter a string: ";

    fgets(str1,sizeof(str1),stdin);

    int n=strlen(str1)-1;

    for(int i=0;i<=n;i++)

    {

        str2[i]=str1[n-i];

    }

    cout<<"Reverse string: "<<str2;

    return 0;

}

 

Java

import java.util.Scanner;

public class Main

{

              public static void main(String[] args) {

                  Scanner sc = new Scanner(System.in);

                             System.out.println("Enter a string: ");

                             String str1 = sc.nextLine();

                             String str2 = "";

                             for(int i=str1.length()-1;i>=0;i--)

                             str2=str2+str1.charAt(i);

                             System.out.println("Reversed string: "+str2);

              }

}

 

Python

str1 = input("Enter a string: ")

print(str1[::-1])


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023
Related Articles

Ask Us Anything !