| Prax (4) | |
|
I am using a divide and conquer method to divide an array till it contains only 4 elements or less , once it contain 4 elements we need to sum the elements which is done by the func sum. below is my code for divide. when i run the program,the if condition is always satisfied and it does the sum of first 4 elements and the rest of the elements the else if condition is not satisfied, please let me know the error. void divide(int a[], int start, int i, int l) { cout<<"Enter Divide"; int q = (i + start)/2; cout<<q<<endl; l++; if (q = 4) { cout<<"Enter Sum"; sum(a,start,(q-1),l); sum(a,q,i,l); return; } else if (q>4) { cout<<"Enter else"; divide(a,start,q,l); divide(a,q,i,l); } } void sum (int a[],int ii, int jj, int l) { int add, counter; cout<<"Enter sum 2"; cout<<"The recurrence level is:"<<l<<endl; for( counter = ii ;counter <= jj; counter ++) { add = add + a[counter]; } cout<<"The sum of the elements of the subproblem is :"<<add<<endl; add = 0; } | |
|
|
|
| ne555 (4383) | |||
| |||
|
|
|||
| Prax (4) | |
| Please let me know the limiting condition coz it is goin into an infinite loop. | |
|
|
|
| ne555 (4383) | |||
Please indent your code and use meaningful names for your variables.
However, your recursive calls are constantly increasing the numbers, so it will not end. | |||
|
|
|||
| Prax (4) | |
|
The if condition above has a return , which will terminate the loop. please inform Wat can be the limiting condition? | |
|
Last edited on
|
|
| Prax (4) | |
|
I could run the below code for 16 elements but when the elements in the array is increased to 32 it again goes into an infinite loop void divide(int a[], int start, int i, int l) { int add1=0; int add2=0; cout<<"Enter Divide"; int q = (i - start)/2; cout<<q<<endl; l++; if (q == 4) { cout<<"Enter Sum"; add1 = a[q+start-4]+a[q+start-1]+a[q+start-2]+a[q+start-3]; cout<<"The sum of the elements is :"<<add1<<endl; cout<<"The level is :"<<l<<endl; add2= a[i-q]+a[i-q+1]+a[i-q+2]+a[i-q+3]; cout<<"The sum is :"<<add2<<endl; return; } else { cout<<"Enter else"; divide(a,start,q,l); divide(a,q,i,l); } } Please let me know how to generalize the above. | |
|
|
|