Click here to Skip to main content
15,071,928 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello.

I have a problem that i hope you can help me with.

I going to get all the negative from this array int[] num = {-5,-4,-3,-2,-1,1,2,3,4,5,6};
and then change the negitive in to positive and then type it out on the screen the negetive that have changed to positive.
Posted
Comments
Richard C Bishop 6-Mar-13 12:41pm
   
So what is the problem?

Hi,

To get all negative integers from the array, try this:
C#
int[] neg = num.Where(x => x < 0).ToArray();

To change the negative numbers in neg into positive numbers, try this:
C#
int[] negToPos = neg.Select(x => Math.Abs(x)).ToArray();

And if you just want to change all negative numbers in num into positive numbers, try this:
C#
int[] pos = num.Select(x => Math.Abs(x)).ToArray();

Hope this helps.
   
Comments
Mike Meinz 6-Mar-13 13:02pm
   
My 5.
Nice!
Thomas Daniels 6-Mar-13 13:04pm
   
Thank you!
ridoy 6-Mar-13 15:16pm
   
+5
Thomas Daniels 7-Mar-13 12:05pm
   
Thank you!
When you get a negative value, reverse the sign like this:
result = -ValueFromArray;
   
Comments
CHill60 6-Mar-13 12:46pm
   
Nice and simple (and clear). My 5
Thomas Daniels 6-Mar-13 13:05pm
   
Good answer, +5!
ridoy 6-Mar-13 15:16pm
   
+5
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cs_Scratch_Console
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[] {-1,-2,0,1,2};
            for (int val = 0; val <= numbers.Length - 1; val++)
            {
                if (numbers[val] < 0)
                {
                    Console.WriteLine(numbers[val]);
                    numbers[val] = Math.Abs(numbers[val]);
                }
            }
        }
    }
}
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900