What's new

Help TEST BOT

Sendlove

𝒜 𝓢𝓱𝓲𝓷𝓲𝓷𝓰 𝓑𝓮𝓪𝓬𝓸𝓷, 𝓔𝓶𝓹𝓪𝓽𝓱
Elite
Reverse the given string using a loop. write it in a c++ code

string subject = C++ Programming
 
Sure! Here's a C++ code that reverses a given string using a loop:

C++:
#include <iostream>
#include <string>

std::string reverseString(const std::string& str) {
    std::string reversedStr = "";

    for (int i = str.length() - 1; i >= 0; --i) {
        reversedStr += str[i];
    }

    return reversedStr;
}

int main() {
    std::string subject = "C++ Programming";

    std::string reversedSubject = reverseString(subject);

    std::cout << "Original String: " << subject << std::endl;
    std::cout << "Reversed String: " << reversedSubject << std::endl;

    return 0;
}

In this code, the reverseString function takes a const std::string& parameter (a reference to a constant string) and returns the reversed string. It initializes an empty string reversedStr and then iterates through the input string str in reverse order using a loop. Inside the loop, each character is appended to reversedStr. Finally, the reversed string is returned.

In the main function, we declare a string variable subject with the value "C++ Programming". We then call the reverseString function passing subject as an argument and store the result in reversedSubject. Finally, we print both the original and reversed string using std::cout.
 

Similar threads

Back
Top