samedi 8 mai 2021

Is there any difference if we apply multiple conditions within for loop rather than giving it in loop body with if else

I have a result array res[3 2 3 5 5 6 0 8 9 0 ] and if the value is not zero then I want to subtract each element with its index. If have written like this

for(int i=0;i<res.length && res[i]!=0;i++)
res[i] =res[i]-i;

this gives an Output res[3,1,1,2,1,1,0,8,9,0]

but when I write like

for(int i=0;i<res.length;i++){
  if(res[i]!=0)
  res[i] =res[i]-i; }

It gives o/p as [3,1,1,2,1,1,0,1,1,0]

I don't understand why the condition within the loop is behaving differently than in IF condition in its body.??

Aucun commentaire:

Enregistrer un commentaire