Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using C++ Please explain what the for loop in this program is doing for each ite

ID: 3909938 • Letter: U

Question

Using C++

Please explain what the for loop in this program is doing for each iteration.

The prompt for the program is as follows: Read a line of text and be able to output it backwards. Example: “You are great!” translates to “!taerg era uoY”.

#include "stdafx.h"

#include <iostream>

#include <string>

using namespace std;

int main()

{

   cout << "This program reverses the order of a word or sentence." << endl << endl;

   cout << "Please enter text: " << endl;

   string UserInput;

   getline(cin, UserInput);

   string reverse;

   for (int i = UserInput.length() - 1; i > -1; i--) {

       reverse = reverse + UserInput.at(i);

   }

   cout << reverse << endl;

}

Explanation / Answer

#include <iostream>

#include <string>

using namespace std;

int main()

{

   cout << "This program reverses the order of a word or sentence." << endl << endl;

   cout << "Please enter text: " << endl;

   string UserInput;

   getline(cin, UserInput);

   string reverse;

   for (int i = UserInput.length() - 1; i > -1; i--) {
// Loop Starts from END, and iterate till the begenning of STRING

//We keep on Accumulation String from END TO START
       reverse = reverse + UserInput.at(i);

   }

// ACCUMULATED string from END TO START is Reverse
   cout << reverse << endl;

}

THANKS, please UPVOTE, Dont forget to HIT THE LIKE BUTTON.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote