unpredictable number of nested loops

  • A+
Category:Languages

I'm trying to make a program that requires nested loops to work properly. But the number of nested loops depend on the number of character the user inputs also the character to output.

This is my code so far.

#include<iostream> using namespace std;   int main(){     string str;     cout<<"Enter some string: ";     cin>>str;      // for two characters     for(int i = 0; i < 2; i++){         for(int j = 0; j < 2 ; j++){             cout<<str[i]<<str[j]<<endl;         }     };      // for four characters     for(int i = 0; i<4; i++){         for(int j=0;j<4;j++){             for(int k =0;k<4;k++){                 for(int z=0;z<4;z++)                     cout<<str[i]<<str[j]<<str[k]<<str[z]<<endl;                 }         }     }     return 0; } 

So, is there any way to solve this issue.

 


You need to do it dynamically:

std::vector<unsigned int> offsets(s.size());  bool isContinue; do {     for(auto offset : offsets)     {         std::cout << s[offset];     }     std::cout << std::endl;      isContinue = false;     for(auto offset = offsets.rbegin(); offset != offsets.rend(); ++offset)     {         if(++*offset < s.size())         {             isContinue = true;             break;         }          *offset = 0;     } } while(isContinue); 

The idea behind is like upcounting numbers (decimally): Once you've reached 9, you increment next digit. Alike, each offset in the vector stands for one loop variable, on 'overflow', increment next offset, and as soon as most significant offset 'overflows', we are done.

High performance variant (using goto, sparing one comparison and the condition variable):

std::vector<unsigned int> offsets(s.size());  NEXT: for(auto offset : offsets) {     std::cout << s[offset]; } std::cout << std::endl;  for(auto offset = offsets.rbegin(); offset != offsets.rend(); ++offset) {     if(++*offset < s.size())         goto NEXT;      *offset = 0; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: