Home > Software design >  How to reverse this loop cpp
How to reverse this loop cpp

Time:01-19

I am trying to get the height of these slashes to be a certain length based on input. So far, I have:

  #include <iostream>
  using namespace std;

  int main() {
  int n = 0;

  cout << "Enter value: ";
  cin >> n;

  cout << "You entered: " << n << "\n";

  for (int i = 1; i <= n; i  ) {
  for (int j = 1; j <= i; j  )
    cout << '/' << '/';

  cout << "\n";
  }
}

I need it to then reverse and go back.

It prints:

//
////
//////

If the user entered 3.

It should print:

//
////
//////
////
// 

Can anyone lead me in the right direction? I am new to cpp.

CodePudding user response:

You can use a different kind of loop and add a bool variable to track when the program have reached "n". Then, after the program reaches "n", it sets the bool variable to true and starts to substract until i equals 0

Code below, read comments and ask if you have any further questions:

#include <iostream>
using namespace std;

int main()
{
    int n = 0;

    cout << "Enter value: ";
    cin >> n;

    cout << "You have entered: " << n << "\n";

    int i = 1;
    bool reachedN = false;  // tells if [i] has reached [n]
    while (i != 0)
    {
        // Print required slashes
        for (int j = 1; j <= i; j  )
        {
            cout << "//";
        }
        cout << '\n'; // new line

        // Add until i == n, then substract
        if (i == n)
        {
            reachedN = true;
        }

        if (reachedN)
        {
            --i;
        }
        else
        {
              i;
        }
    }
}

If you enter 3, the output is the following:

Output

CodePudding user response:

This is one way to achieve that:

  #include <iostream>
  using namespace std;

  int main() {
  int n = 0;

  cout << "Enter value: ";
  cin >> n;

  cout << "You entered: " << n << "\n";

  for (int i = 1; i <= n; i  ) {
  for (int j = 1; j <= i; j  )
    cout << '/' << '/';

  cout << "\n";
  }
  for (int i = n - 1; i > 0; i--) {
  for (int j = 1; j <= i; j  )
    cout << '/' << '/';

  cout << "\n";
  }
}

CodePudding user response:

This is a shorter solution with only two for-loops.

#include <iostream>
    
    using namespace std;
    
    int main()
    {
        int n = 0;
    
        cout << "Enter value: ";
        cin >> n;
    
        cout << "You entered: " << n << "\n";
    
        n = n * 2 - 1;
        int r = 0;
    
        for (int j = 0; j < n; j  )
        {
            if (j > n / 2) r--;
            else r  ;
    
            for (int i = 0; i < r; i  )
            {
                cout << '/' << '/';
            }
    
            cout << "\n";
        }
        
    
        return 0;
    }
  •  Tags:  
  • Related