Wednesday, March 15, 2023

Write a program in C++ that display entered string into reverse order

Reverse String Program in C++ - Display String in Reverse Order

Write a program in C++ that display entered string without using library into reverse order. Learn how to write a program in C++ that displays a user-entered string in reverse order. This program uses a for loop and does not rely on any library functions.

#include <iostream>
using namespace std;

int main()
{
    char str[100];

    cout << "Enter a string: ";
    cin.getline(str, 100);

    int len = 0;
    while (str[len] != '\0') // calculating the length of the string
    {
        len++;
    }

    cout << "Reverse of the string is: ";

    for (int i = len - 1; i >= 0; i--)
    {
        cout << str[i];
    }

    return 0;
}

Explanation:

  • #include <iostream> is the header file used in the program. It is for input/output operations.
  • using namespace std; is a directive that allows us to use the standard namespace, which contains the standard C++ library.
  • char str[100]; declares a character array of size 100 to store the entered string.
  • cout << "Enter a string: "; prints the message to the console asking the user to enter a string.
  • cin.getline(str, 100); reads the string entered by the user and stores it in the str variable.
  • The while loop is used to calculate the length of the string entered by the user. It iterates over the string until it reaches the null character '\0' which marks the end of the string.
  • The for loop is used to iterate over the string in reverse order. It starts from the last character of the string and prints each character in reverse order to the console using cout.
  • return 0; terminates the program and returns a value of 0 to the operating system, indicating that the program executed successfully.

No comments:

Post a Comment

Write a c++ program to show the difference between an array and a list.

Array vs List Example Write a c++ program to show the difference between an array and a list. Arrays are useful when you know the number ...