Search code examples
c++nested-loops

nested looping C++


i want to asking this problem. this output is the expected output

*
*#
*#%
*#%*
*#%*#
*#%*#%

and this is my solution

#include <iostream>

using namespace std;


int main(){

  int a,b,n;

  cout << "Input the row";
  cin >> n;


  for (a = 1; a <= n; a++){
    for(b = 1; b <= a; b++){
        if (b == 1 || b == 1 + 3){
            cout << "*";
        }
        if (b ==2 || b == 2 + 3){
            cout << "#";
        }
        if (b ==3 || b == 3 + 3){
            cout << "%";
        }
    }
    cout << endl;
  }
}

this solution is only work if the n = 6. what should i do if i want this work in every row when user input the row to the n thank you in advance.


Solution

  • Here, I tried using the modulo "%" on your if's

    #include <iostream>
    
    using namespace std;
    
    
    int main(){
    
      int a,b,n;
    
      cout << "Input the row";
      cin >> n;
    
    
      for (a = 1; a <= n; a++){
        for(b = 1; b <= a; b++){
            // After every first digits will cout #
            if (b % 3 == 2){
                cout << "#";
            }
            // The first after the third digit will cout *
            if (b % 3 == 1){
                cout << "*";
            }
            // The third digit after the second digit will cout % 
            if (b % 3 == 0){
                cout << "%";
            }
        }
        cout << endl;
      }
    }