473,511 Members | 17,164 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help on N nested for loops, where N is a variable!!

3 New Member
Basically what I am trying to do is a N nested for loops, where N is an input variable. How to write a single piece of codes to take care of different N?
Thanks!
Aug 2 '07 #1
8 10322
Meetee
931 Recognized Expert Moderator Contributor
Basically what I am trying to do is a N nested for loops, where N is an input variable. How to write a single piece of codes to take care of different N?
Thanks!
I am not clear with your explanation. You want to make N for loops!!!??? You mean to say you want to run N nested loops?? Kindly elaborate.

Regards
Aug 2 '07 #2
dickld
3 New Member
I am not clear with your explanation. You want to make N for loops!!!??? You mean to say you want to run N nested loops?? Kindly elaborate.

Regards
For example, if N = 2, we want a two layer nested loop.
for (int i = 0; i < 10; i++)
for (int j = 0; j < 20; j++)
{
......
}

if N=3, we want a three layer nested loop
for (int i = 0; i < 10; i++)
for (int j = 0; j < 20; j++)
for (int k=0; k< 30; k++)
{
......
}

So on and so forth. Since N can take any value between 1 and 10, I have to write 10 different nested loops, each for a value of N. It is no good. It would be great if there is a way to use one single piece of codes to do all the business.
Thanks.
Aug 2 '07 #3
Banfa
9,065 Recognized Expert Moderator Expert
I would say you have 2 options

1. Use a recursive function, that is a function taht calls itself to set up the right number of for loops

2. Use a single for loop, calculate the total number of iterations that your 'nested' loops would give and loop for that many iterations and calculate the values of i' j' k ... on each iteration of the loop.
Aug 2 '07 #4
JosAH
11,448 Recognized Expert MVP
2. Use a single for loop, calculate the total number of iterations that your 'nested' loops would give and loop for that many iterations and calculate the values of i' j' k ... on each iteration of the loop.
That could cause integer overflows earlier than you'd expected them. There's
a third way: use three int arrays:

1) lo: containing the low values of the n loops
2) hi: containing the hi values of the n loops
3) val: initially equal to array lo.

The following little function produces the next values in array val: if the last values
have been reached already the method returns NULL

Expand|Select|Wrap|Line Numbers
  1. int[] loopn(int[] lo, int[] hi, int[] val, int n) {
  2.    int i;
  3.    for (i= n; i-- > 0; )
  4.       if (++val[i] >= hi[i])
  5.          val[i]= lo[i];
  6.       else
  7.          return val;
  8.    return NULL;
  9. }
kind regards,

Jos
Aug 2 '07 #5
dickld
3 New Member
Thanks for your helps.

For the third method, I do not think it goes through all the combination of the values of i,j,k....
Am I right?
Aug 2 '07 #6
BugMeNot2013
1 New Member
I came across this earlier today and thought I might share the solution that I eventually came up with. (I realise that this question is 6 years old, but I'm thinking it might still come in handy for somebody one day!)

I think it should be pretty efficient. Also, it doesn't use any specific c++ stuff - it will work fine on C as well.

We're trying to create N nested "for" loops.
Instead of using
Expand|Select|Wrap|Line Numbers
  1. for(int i = 0; i<max; i++)
  2.   for (int j = 0; j<max; j++)
  3.     ...
  4.  
I'll be replacing i, j, ... with an array: i[0], i[1], ..., i[n-1].

Here's my solution:
Expand|Select|Wrap|Line Numbers
  1. const int n = /*Insert N here: how many loops do you need?*/;
  2. int i[n+1]; // if "n" is not known before hand, then i[n+1] will need to be created dynamically.
  3. //Note: there is an extra element at the end of the array, in order to keep track of whether to exit the array.
  4.  
  5. for (int a=0; a<n+1; a++) {
  6.   i[a]=0;
  7. }
  8.  
  9. int MAX = 79; //That's just an example, if all of the loops are identical: e.g. "for(int i=0; i<79; i++)". If the value of MAX changes for each loop, then make MAX an array instead: (new) int MAX [n]; MAX[0]=10; MAX[1]=20;...;MAX[n-1]=whatever.
  10.  
  11. int p = 0; //Used to increment all of the indicies correctly, at the end of each loop.
  12. while (i[n]==0) {//Remember, you're only using indicies i[0], ..., i[n-1]. The (n+1)th index, i[n], is just to check whether to the nested loop stuff has finished.
  13.   //DO STUFF HERE. Pretend you're inside your nested for loops. The more usual i,j,k,... have been replaced here with i[0], i[1], ..., i[n-1].
  14.   //DO STUFF
  15.   //DO STUFF
  16.  
  17.   //Now, after you've done your stuff, we need to incrememnt all of the indicies correctly.
  18.   i[0]++;
  19.   // p = 0;//Commented out, because it's replaced by a more efficient alternative below.
  20.   while(i[p]==MAX) {//(or "MAX[p]" if each "for" loop is different. Note that from an English point of view, this is more like "if(i[p]==MAX". (Initially i[0]) If this is true, then i[p] is reset to 0, and i[p+1] is incremented.
  21.     i[p]=0;
  22.     i[++p]++; //increase p by 1, and increase the next (p+1)th index
  23.     if(i[p]!=MAX) {
  24.       p=0;//Alternatively, "p=0" can be inserted above (currently commented-out). This one's more efficient though, since it only resets p when it actually needs to be reset!
  25.     }
  26.   }
  27. }
  28.  
There, that's all. Hopefully the comments make it clear what it's meant to be doing. I think it should be pretty efficient - almost as much as real nested for-loops. Most of the overhead is a one-off at the beginning, so this should be more efficient that using recursive functions etc.

Hope it's useful to somebody one day.

Peace and love.
Dec 13 '13 #7
weaknessforcats
9,208 Recognized Expert Moderator Expert
This solution is WAY too complicated. All that's needed is a function that calls the correct number of loops with the correct number of iterations.

So write a loop function:
Expand|Select|Wrap|Line Numbers
  1. void loop(int N)
  2. {
  3.     switch (N)
  4.     {
  5.      case 10:
  6.          loopi(N);
  7.          break;
  8.      case 20:
  9.          loopj(N);
  10.          break;
  11.      case 30:
  12.          loopk(N);
  13.          break;
  14.     } /* end of switch */
  15. }
  16.  
This function tests the value of N and then calls a secondary function using the value of N.

So all the user needs is to call this function with N:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.    int N = 30;
  4.    loop(N);
  5.  
  6.    N = 20;
  7.    loop(N);
  8.  
  9.  
  10.    N = 10;
  11.    loop(N);
  12.  
  13. }
The secondary functions know about the nested loops and the iterations of the nested loops:

Expand|Select|Wrap|Line Numbers
  1. void loopi(int N)
  2. {
  3.     //do loop i and return
  4.     printf("Loop i  %d\n", N);
  5.     return;
  6. }
  7. void loopj(int N)
  8. {
  9.         loopi(N - 10);
  10.         // do loop j
  11.         printf("Loop j %d\n",N);
  12.         return;
  13. }
  14. void loopk(int N)
  15. {
  16.         loopj(N - 10);
  17.         //do loop k
  18.         printf("Loop k %d\n", N);
  19.         return;
  20. }
You might run this code to get a feel for how it works.
Dec 14 '13 #8
Banfa
9,065 Recognized Expert Moderator Expert
@weaknessforcats your solution only allows for up to 3 nested loops but the solution calls for up to N nested loops.

@BugMeNot2013 I disagree with weaknessforcats I think your code is not complex enough since it fails to achieve the required solution. Note that in the original question the first loop has an iteration limit of 10, the second 20, the third 30 etc. This behaviour is not demonstrated in your code. Also I think your are wrong at line 19 because the you repeated run the if at 24 and then always (by the logic of the loop) run the assignment at 25. The best you do is replace an assignment with a single if when i[0]<MAX but generally conditionals (if) are less efficient than assignments. I think this is a case of trying to be too clever.

I suspect the solution suggested by JosAH is probably the best although I find the logic of his code snippet strange/wrong.
Dec 16 '13 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

3
5104
by: Oleg Leschov | last post by:
Could there be means of exiting nested loops in python? something similar to labelled loops in perl.. I consider it irrating to have to make a flag for sole purpose of checking it after loop if...
0
1779
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # David Eppstein of the Geometry Junkyard fame gave this elegant # version for returing all possible pairs from a range of n numbers. def combo2(n): return...
46
9872
by: Neptune | last post by:
Hello. I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)" (Sam's series), and for nested loops, he writes (p116) "It's often necessary to create a loop even when you are...
10
1859
by: Pavan | last post by:
Hi i have two nested loops as shown below: 1. for(i=0;i<=1000;i++) { for(i=0;i<=100;i++) { .....; .....; }
10
2018
by: Roshawn | last post by:
Hi, I am experimenting with nested For...Next loops. My code looks like this: Dim i as Byte Dim itm as Byte For i = 0 to 9 For itm = 0 to 9 'code omitted
77
5152
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop....
3
1924
by: tzuriel | last post by:
Hello all, I think nested loops will do what I want, but I can't seem to get them right. I have two tables, members and casts. I run a query as follows: $sql_query="SELECT DISTINCT...
3
1721
by: rkc | last post by:
Hi, I need to design the following pattern using just the 'for' and the 'if, else' statement. Please provide some help.. thanks in advance: ********** !********* !!******** !!!*******...
4
2323
by: toddlahman | last post by:
I am using two while loops that are nested. The first loop (post name) returns the full column of results, but the second (post modified) only returns the first row of the column. Is there another...
0
7245
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7144
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
7085
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5671
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5069
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4741
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3214
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1577
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.