C++ code to find array from given array with conditions


Suppose we have an array A with n elements. There is another hidden array B of size n. The elements can be negative or positive. For each index i in range 1 to n, following operations will be performed −

  • Set A[i] as 0 initially

  • Then add B[i] to A[i], subtract B[i+1], then add B[i+2] and so on

We have to find the array B.

So, if the input is like A = [6, -4, 8, -2, 3], then the output will be [2, 4, 6, 1, 3]

Steps

To solve this, we will follow these steps −

for initialize i := 0, when i < size of A, update (increase i by 1),
do:
   print (A[i] + A[i + 1])

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A){
   for (int i = 0; i < A.size(); i++)
      cout << A[i] + A[i + 1] << ", ";
}
int main(){
   vector<int> A = { 6, -4, 8, -2, 3 };
   solve(A);
}

Input

{ 6, -4, 8, -2, 3 }

Output

2, 4, 6, 1, 3,

Updated on: 29-Mar-2022

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements