Thread: Is there any specific method to turn an array value from positive to negative?

  1. #1
    Registered User
    Join Date
    Oct 2019
    Posts
    43

    Is there any specific method to turn an array value from positive to negative?

    Hi everyone,
    Is there any specific technique to turn all of the array values from positive to negative?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,656
    A for loop with a[i] = -a[i]; perhaps?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    502
    Quote Originally Posted by Shafiul View Post
    Hi everyone,
    Is there any specific technique to turn all of the array values from positive to negative?
    If they are all non-negative, just set to the negative, as Salem suggests. Note that in C, = means "assign".

    If some are negative, and you want them all to be negative, then you need to test them first, then sign flip the positive ones.

    Note that because of how binary numbers work, INT_MIN is one lower than -INT_MAX. This won't affect you as you are converting from positive to negative. However if you do the reverse conversion you need to test for INT_MIN and flag an error.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Get a positive/negative input from user
    By never_lose in forum C Programming
    Replies: 2
    Last Post: 04-12-2011, 06:36 PM
  2. Replies: 16
    Last Post: 11-27-2010, 11:44 PM
  3. convert negative float to positive ???
    By manny in forum C Programming
    Replies: 4
    Last Post: 07-02-2009, 03:37 AM
  4. Changing from positive to negative numbers
    By vopo in forum C++ Programming
    Replies: 19
    Last Post: 09-10-2008, 02:21 PM
  5. Negative Float Into Positive
    By Cero.Uno in forum C Programming
    Replies: 2
    Last Post: 02-17-2008, 03:13 AM

Tags for this Thread