find difference of sum of elements at even indices (E) and sum of elements at odd indices(O). c++

 Find the Difference

Given an array/list A with N elements, you need to find difference of sum of elements at even indices (E) and sum of elements at odd indices(O).

Note : Array/List indexes start from 0.

Input Format :
  Line 1 : Size of the array/list i.e N
  Line 2 : N integers i.e. elements of the array/list separated by space
Output Format :
 Difference i.e. E - O.  
Input Constraints :

1<=N<=10^6

1 <= Ai <= 10^4

Sample Input :
5
1 2 3 4 5
Sample Output :
3
Sample Output Explanation :

Sum of elements at even indices = 1 + 3 + 5 = 9

Sum of elements at odd indices = 2 + 4 = 6

So output is (9 - 6) i.e. 3.


c++ code:


#include <iostream>
using namespace std;

int main(){
     int A[1000000];
  
  int n;
  cin>>n;
  for(int i=0;i<n;i++)
  {
    cin>> A[i];
  
  }
  int even=0;
  for(int i=0;i<=n;i+=2)
  {
    even+=A[i];
  }
  int odd=0;
  for(int i=1;i<=n;i+=2)
  {
    odd+=A[i];
  }
  
  cout<< even-odd;
}





SHARE

Milan Tomic

Hi. I’m Designer of Blog Magic. I’m CEO/Founder of ThemeXpose. I’m Creative Art Director, Web Designer, UI/UX Designer, Interaction Designer, Industrial Designer, Web Developer, Business Enthusiast, StartUp Enthusiast, Speaker, Writer and Photographer. Inspired to make things looks better.

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment