c++ - Alternate highest counting in array -
i have array sorted contains zeroes in between
a[10]={0,0,3,5,0,6,7,0,9,0} i want neglect zeroes , find sum of alternate elsments i.e. 3+6+9 , 5+7 seperately. here m trying do
while(i<10) { if(a[i]!=0) { s1=s1+a[i]; i++; } if(a[i]!=0) { s2=s2+a[i] i++; } i++; } any alternate this??
use boolean keep track of sum add element to:
bool alt = true; int sum1 = 0; int sum2 = 0; for(int = 0; i<10; ++i) { if(a[i]) { if(alt) { sum1 += a[i]; } else { sum2 += a[i]; } alt = !alt; } }
Comments
Post a Comment