Home > other >  How can I multiply every element in array by -1 in c
How can I multiply every element in array by -1 in c

Time:04-05

I have an array of elements and I want to multiply every element in that arr with -1 and store it in another array.

int arr1[] ={1,0,1,1,1,0,0,1}
int outputArr[]= {-1,0,-1,-1,-1,0,0,-1};

How do I do it? I know I can iterate over the loop one at a time but I am looking for a function or something (if it exists ) so that I can preferably do that in a single line.

CodePudding user response:

You can use std::tranform to apply a unary operation to each element.

std::transform( std::begin( arr1 ), std::end( arr1 ), std::begin( output ), []( int val ) { 
    return val * -1; 
});

You could also use std::negate, but keep in mind this is not a multiplication, but instead applies operator-()

std::transform( std::begin( arr1 ), std::end( arr1 ), std::begin( output ), std::negate<int>() );

Note: std::begin and std::end will only work for the array if arr1 is defined in the same function (i.e. not a parameter to a function).

Also note that output must be (at least) the same size as arr1.

CodePudding user response:

  1. Create an output array with the same size of the input array. You can use std::size for this since C 17.
  2. Walk it, e.g. using std::transform, and, for each element n, just have transform return -n.
#include <algorithm>  // transform
#include <fmt/ranges.h>

int main()
{
    int arr1[] = {1,0,1,1,1,0,0,1};
    int outputArr[std::size(arr1)];
    std::ranges::transform(arr1, std::begin(outputArr), [](auto& n) { return -n; });
    fmt::print("arr1 = {}\n", arr1);
    fmt::print("outputArr = {}\n", outputArr);
}

// Outputs:
//
//   arr1 = [1, 0, 1, 1, 1, 0, 0, 1]
//   outputArr = [-1, 0, -1, -1, -1, 0, 0, -1]
  •  Tags:  
  • c
  • Related