Hanson
Hanson

Reputation: 35

Changing the loop approach to another one

I change the code :

for(double i=0;i<=1;i+=a){//0<a<1
    for(double j=0;j+i<=1;j+=c){//0<c<1
        [...]
    }
}

To:

for(int i=0;i<100;i++){
    do {
        iCycle[i]=i*a;
        for(int j=0;j<100;j++){
            do{
                jCycle[j]=j*c;
            }
            while(iCycle[i]+jCycle[j]<=1);  
            jCycleNum=j;
        }
    }
    while(iCycle[i]<=1);
    iCycleNum=i;
}

for(int i=0;i<iCycleNum;i++){
    for(int j=0;j<jCycleNum;j++){
        [...]
    }
}

I change the approach because I want to get the value of the iCycleNum and jCycleNum,iCycleNum is the loop number of the for(double i=0;i<=1;i+=a), the jCycleNum is the loop number of the for(double j=0;j+i<=1;j+=c). But I think something wrong is happened in my new code. What am I missing? Can somebody help me ?

Add: I want to get the loop number of for(double i=0;i<=1;i+=a) and for(double j=0;j+i<=1;j+=c) , and the every loop the value of i and j then put them in array .

Upvotes: 0

Views: 107

Answers (1)

Łukasz Daniluk
Łukasz Daniluk

Reputation: 470

Both codes are not equivalent, as iCycleNum will always be 99.

If you want number of iterations of each loop you can add this variable to your first code.

Since you cannot use vector we have a little problem. If you know maximum iterations at compile time you can do something like this (I assumed the max is equal for both i and j):

double iCycle[maxIters], jCycle[maxIters];

int iCycleNum = 0, jCycleNum = 0;
for(double i=0; i<=1; i+=a, ++iCycleNum){//0<a<1
    iCycle[iCycleNum] = i;
    for(double j=0; j+i<=1; j+=c, ++jCycleNum){//0<c<1
        jCycle[jCycleNum] = j;
        [...]
    }
}

In case you don't know maxIters at compile time and at runtime, you will need to change first line to:

dobule *iCycle, *jCycle;
iCycle = new double[maxIters];
jCycle = new double[maxIters];

But in this case you have to remember to do:

delete[] iCycle;
delete[] jCycle;

When you are done.

Is this solution to your problem?

Upvotes: 2

Related Questions