0

Here is the main portion of my code where "while" loop:

while(ind1<n1.length && ind2<n2.length)
       {
           if(ncm!=null)
           {
              if(n1[ind1]<ncm)
              {
                  s1=s1+n1[ind1];
                  ind1++;
              }
              else if(n2[ind2]<ncm)
              {
                 s2=s2+n2[ind2];
                  ind2++;
              }
              else if(n2[ind2]==ncm && n1[ind1]==ncm)
              {
                  s2=s2+n2[ind2];
                  s1=s1+n1[ind1];
                  
                  if(s1>s2)
                      s2=s1;
                  else if(s2>s1)
                      s1=s2;
                  
                  
                  
                  
                  ind1++;
                  ind2++;
                 ncm=q.poll();  
              }
           }
           else
           {
                 s1=s1+n1[ind1];
                  ind1++;
              
                   s2=s2+n2[ind2];
                  
                  ind2++;
             
           }

            System.out.println("ind1 "+ind1+" ind2 "+ind2);
            System.out.println("s1 "+s1+" s2 "+s2);
           
       }

I am passing these two arrays: int n1[]= {1,2,3,4}; int n2[]= {10,11};

I have observed which array has minimum elements the loop is getting terminated upto that last index of the minimum array while I want it may continue till it reaches both the array's last element. Isn't this condition suffice ? " while(ind1<n1.length && ind2<n2.length) "

3 Answers 3

2

No, this condition

while(ind1<n1.length && ind2<n2.length)

Will mean that if one of the comparisons ends up false, the while loop will end. That will happen when it reaches the shortest array's last element. Instead, if you want to continue until it reaches the longest array' last element, it should be:

while(ind1<n1.length || ind2<n2.length)
Sign up to request clarification or add additional context in comments.

1 Comment

It worked but had to add extra logic in else statement if(ind1<n1.length) { s1=s1+n1[ind1]; ind1++; } if(ind2<n2.length) { s2=s2+n2[ind2]; ind2++; }
0

If you want to reach the end of both arrays, you should add conditional OR instead of AND:

while(ind1<n1.length || ind2<n2.length)

Comments

-1

How about <=(Less Then Equal to)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.