Search code examples
c++for-loopif-statementvectorreturn

Return Statement positioning


I am writing some function which basically takes in input a range and a 1D vector. It looks at each number in the range of values given of the vector such that:

1) If the number to the left of it is 0 they swap positions.

2) If the number to the left of it is equal to it they add.

Now up till now this was good. The issue arises when I am trying to add return statements:

1) It should return True after all iterations are complete and at least one of the if conditions is entered in each iteration.

2) It should return false after all iterations are complete and none of the conditions are entered.

Now if I put these return statements in the loops they would terminate this function here but this is not desirable since it needs to go through all the iterations first. Is the current code comparable with this or do I need to redo it in a different manner ( if not where could the return statements go?)


Solution

  • bool proc_num(std::vector<int>&v, int LB, int UB) {            
        bool check = false;
        for( int i=LB+2 ; i<UB; i++) {
            for(int j = i-1; j>LB; j--) {
                if(v[j] == 0){
                    v[j] = v[i];
                    check = true;
                } else if(v[j] == v[i]) {
                    v[j]= v[j]+v[i];
                    v[i] = 0;
                    check = true;
                }
            }
        }
        return check;
    }
    

    You can simply add a boolean to make sure that at least one of the if conditions are entered.