Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 0.99 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. how to add a sum of even and odd number of an array
  2. int calc(int *a, int size)
  3. {
  4.     if(size==1 || size==0)
  5.         return a[0];
  6.     for(int i=0; i<size; i++){
  7.         if(i%2==0){
  8.             int sum_i = a[i];
  9.             int m=calc(a, size-1);
  10.             if(m>a[size-1])
  11.                 return m;
  12.         }
  13.     }
  14.     for(int j=0; j<size; j++){
  15.         if(j%2!=0);
  16.         int sum_j = a[j];
  17.         return sum_j;
  18.     }
  19.     int sum = a[i] - a[j];
  20.     int e = calc(a, size-1);
  21.     if(e%2==0)
  22.         return e=e+0; //return even
  23.  
  24.     return sum;
  25. }
  26.  
  27. int main( )
  28. {
  29.     int a[6]={1,2,3,5,6,2};
  30.     int size = 6;  
  31.     cout<< calc(a, size)<<endl;
  32.  
  33.     system("pause");  
  34.     return 0;
  35. }
  36.        
  37. // calc(): returns sum(a[0], a[2], a[4], ...) - sum(a[1], a[3], a[5], ...)
  38. int calc(int *a, int size)
  39. {
  40.     int sum_even_pos = 0;
  41.     int sum_odd_pos = 0;
  42.     for (int i = 0; i < size; i++)
  43.     {
  44.         sum_even_pos += a[i];
  45.         if (++i < size) sum_odd_pos += a[i];
  46.     }
  47.     return sum_even_pos - sum_odd_pos;
  48. }