Want to convert -ve value to +ve

This is a discussion on Want to convert -ve value to +ve within the C Programming forums, part of the General Programming Boards category; hi, i have a looop ... in which i am adding one value to another. what i wish is to ...

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    17

    Want to convert -ve value to +ve

    hi, i have a looop ... in which i am adding one value to another.

    what i wish is to run the loop till the index is greater than -5 and in the loop i want to print only +ve value of the index.

    i.e

    Code:
    int index =0;
    for (index = 5; index >= -5; index--){
        printf ("%d", index);
    }
    it will print
    Code:
    543210-1-2-3-4-5
    but i want only
    Code:
    54321012345
    actually i was thinking to manipulate bits.

  2. #2
    Registered User marrk's Avatar
    Join Date
    Sep 2006
    Posts
    23
    In the for loop make if statement where you will multiply index lower then 0 with -1.
    Last edited by marrk; 09-05-2006 at 01:40 AM.

  3. #3
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,069
    Alternatively, you could use <math.h> and its absolute value function.
    Code:
    /* Make sure to
    #include <math.h>
    */
    
    int index;
    for (index = 5; index >= -5; index--)
       printf ("%d", abs(index));
    actually i was thinking to manipulate bits.
    Manipulating bits would be overly complicated and not at all portable as different systems will store negative values in different ways, usually with either Two's Complement, One's Complement, or Sign Magnitude. Even if you bothered to analyse how your computer is storing them, it still wouldn't work on every other computer.
    Last edited by SlyMaelstrom; 09-05-2006 at 02:00 AM.
    Sent from my iPadŽ

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. Convert to int
    By abyu in forum C++ Programming
    Replies: 7
    Last Post: 11-12-2006, 07:05 AM
  3. Replies: 3
    Last Post: 08-21-2006, 06:42 AM
  4. Convert Char to Int Function
    By drdroid in forum C++ Programming
    Replies: 9
    Last Post: 02-19-2003, 11:53 AM
  5. please help ... to convert date to string
    By mel in forum C Programming
    Replies: 1
    Last Post: 06-12-2002, 10:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21