unpredictable number of nested loops

nested for loop python
nested loop in python w3schools
nested while loop in python
python nested for loop variable scope
python nested for loop same variable
inner loop and outer loop in python
python break nested loop
python reset variable in loop

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;
}

Data-driven Graphic Design: Creative Coding for Visual Communication, Nesting two “for” loops, one inside another, is used to create a “grid” of shapes. predictable number sequences that can be applied to create visual variety. I am working on a compiler optimisation routine for GPUs that optimises nested loops which has unpredictable number of iterations. To test my routine I need some real-life algorithms that include this kind of loop construct.

There are a couple basic ways to do that looping.

The first is the explicit one: you need to use an array of indexes instead of a single variable for the loop index. Then at each step you increment the last index and when that gets past the limit you reset it and increment the previous one:

int n = str.size(); // Get rid of unsigned
std::vector<int> index(n);
for(;;) {
    // Generate output
    for (int i=0; i<n; i++) {
        std::cout << str[index[i]];
    }
    std::cout << std::endl;

    // Increment
    int i = n-1; // start from last index
    while (i>=0 && index[i] == n-1) {
        // I-th index has reached the end of the string, flip over to 0
        index[i] = 0;
        --i;
    }
    if (i == -1) break; // all of them returned to 0... that's all, folks
    index[i] += 1;
}

The second way is using recursion, for example with a function accepting the partial string being built as argument and that if this prefix is not complete loops over the string and calls itself passing an extended prefix:

std::function<void(const std::string&)> proc = [&](const std::string& prefix) {
    if (prefix.size() == str.size()) {
        // Prefix is complete, just output result
        std::cout << prefix << std::endl;
    } else {
        // Extend the prefix and call yourself for the nested loops
        for (int j=0; j<n; j++) {
            proc(prefix + str[j]);
        }
    }
};
proc("");

The recursive approach is more compact but takes some time to become comfortable and it can be problematic in certain cases.

A different way avoiding nested loops be to use simple counting and math... it's easy to write a function that returns the n-th string you're looking for without looping over the previous ones...

for (int i=0,loops=pow(n, n); i<loops; i++){
    std::string s = "";
    int k = i;
    for (int j=0; j<n; j++) {
        s = str[k % n] + s;
        k /= n;
    }
    std::cout << s << std::endl;
}

Nested loops with same variable reused after inner loop body , This may lead to unexpected behavior if the loop variable is used after the inner This example shows a function that processes a sequence of lists of numbers. Nested Loops Join. For a nested loops join, the chance of getting a lazy table spool increases in line with: The estimated number of rows on the outer input of the join. The estimated cost of inner-side plan operators. The cost of the spool is repaid by savings made avoiding inner-side operator executions.

Let's fold all your N nested loops into one nested loop. First, we need N indices, which will be incremented properly:

class Multiindex
{
public:
    Multiindex(int size, int last_) : idx(size,0), last(last_) {}

    void inc()
    {
        for (int i = idx.size() - 1; i >= 0; --i) {
            if (idx[i] == last - 1) {
                idx[i] = 0;
                if (i == 0) complete = true;
            }
            else {
                ++idx[i];
                break;
            }
        }
    }

    const auto& getIdx() const { return idx; }
    const auto isComplete() const { return complete; }

private:
    std::vector<int> idx;
    int last;
    bool complete = false;
};

It's a minimal example of a multiindex class. You also may write a decrement method or use a vector of last indices, if you need different indices in your nested loop.

Now everything is ready to replace your nested loop:

std::string s;// From user
Multiindex midx(s.length(), s.length());
while (!midx.isComplete()) { // Your nested loop
    const auto& idx = midx.getIdx();
    for (int i = 0; i < idx.size(); ++i) { // Replacement for cout << s[i] << s[j] << ... << s[z] << endl;
        std::cout << s[idx[i]];
    }
    std::cout << std::endl;
    midx.inc();
}

Techniques for Building Timing-Predictable Embedded Systems, 7–10 we see that in general adding nested-loop optimization can significantly the memory blocks mapped to one cache set in an inner loop are too many to  A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa. Example. The following program uses a nested for loop to find the prime numbers from 2 to 100 −

Looking for algorithms with nested loops with unpredictable iteration , I am working on a compiler optimisation routine for GPUs that optimises nested loops which has unpredictable number of iterations. To test my  A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.

Teach Your Kids to Code: A Parent-Friendly Guide to Python Programming, and classes that can be reused in other programs. nested loop A loop inside random numbers An unpredictable sequence of numbers evenly distributed  If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the nested for loop. for (int i = 1; i <= 5; ++i) { // codes inside the body of outer loop for (int j = 1; j <=2; ++j) { // codes inside the body of both outer and inner loop } // codes inside the body of outer loop } Here, a for loop is inside the

Intro Prgrm Logic Quiz 6 Capt 6 Flashcards, Numbers that form an unpredictable sequence in which each number is In a program with nested loops, the outer loop is completed ______  Nested loops have performance considerations (see @Travis-Pesetto's answer), but sometimes it's exactly the correct algorithm, e.g. when you need to access every value in a matrix. Labeling loops in Java allows to prematurely break out of several nested loops when other ways to do this would be cumbersome.

Comments
  • You need to improve your algorithm. Think of at as looping through all loops. Use a multiindex to get all indices you would have in the most nested loop.
  • @Yola You're right, thanks for the hint... Iterating over the indices in reverse order now. Should I pretend I applied the famous da Vinci strategy?
  • the famous da Vinci strategy?
  • @Yola da Vinci deliberately introduced errors into his sketches so that if someone stole them, they were of little use - and he could prove ownership by knowing how to do it right...
  • @Yola Suppose it's the most famous one: leonardodavincisinventions.com/wp-content/uploads/2012/02/… Note that if constructed as presented, front and rear wheels would rotate in opposite directions.
  • You have a wild goto NEXT in your first code snippet (the one without labels). Presumably a mistake?