C++ Program to find an array satisfying an condition

C++Server Side ProgrammingProgramming

Suppose, we are given an array of n integers 'x'. We have to find out another array of integers 'y', so that x[1].y[1] + x[2].y[2] +...+ x[n].y[n] = 0. We print the contents of array y.

Problem Category

Various problems in programming can be solved through different techniques. To solve a problem, we have to devise an algorithm first, and to do that we have to study the particular problem in detail. A recursive approach can be used if there is a recurring appearance of the same problem over and over again; alternatively, we can use iterative structures also. Control statements such as if-else and switch cases can be used to control the flow of logic in the program. Efficient usage of variables and data structures provides an easier solution and a lightweight, low-memory-requiring program. We have to look at the existing programming techniques, such as Divide-and-conquer, Greedy Programming, Dynamic Programming, and find out if they can be used. This problem can be solved by some basic logic or a brute-force approach. Follow the following contents to understand the approach better.

So, if the input of our problem is like n = 6, x = {4, 6, 3, 8, 5, 7}, then the output will be -6 4 -8 3 - 7 5

Steps

To solve this, we will follow these steps −

for initialize i := 0, when i < n, update i = i + 2, do:
   a := x[i]
   b := x[i + 1]
   print( - 1 * b followed by a space and a)

Example

Let us see the following implementation to get better understanding −

#include<bits/stdc++.h>
using namespace std;
void solve(int n, int x[]) {
   for(int i = 0; i < n; i = i + 2){
      int a = x[i];
      int b = x[i + 1];
      cout<< -1 * b << " " << a << " ";
   }
}
int main() {
   int n = 6, x[] = {4, 6, 3, 8, 5, 7};
   solve(n, x);
   return 0;
}

Input

6, {4, 6, 3, 8, 5, 7}

Output

-6 4 -8 3 -7 5
raja
Updated on 07-Apr-2022 08:46:43

Advertisements