C# - Convert Negative Values to Positive in an Array

Here, we are going to learn how to convert negative values an integer array into positive in C#?
Submitted by Nidhi, on August 22, 2020 [Last updated : March 19, 2023]

Here we will create an array of integers that will contain negative and positive integers. Here we will convert negative values into positive values and then print all elements on the console screen.

C# program to convert negative values to positive in an array

The source code to convert negative values of an array into positive is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

// C# program to convert negative values 
//an integer array into positive.

using System;

class Demo
{
    public static void Main()
    {
        int[] arr = { 10, -20, 30, -40, 50, -60, 70 };
        int loop = 0;
        
        for (loop = 0; loop < arr.Length; loop++)
        {
            if (arr[loop] < 0)
                arr[loop] = -arr[loop];
        }

        Console.WriteLine("Array elements after conversion:");
        for (loop = 0; loop < arr.Length; loop++)
        {
            Console.Write(arr[loop]+" ");
        }
        Console.WriteLine();
    }
}

Output

Array elements after conversion:
10 20 30 40 50 60 70
Press any key to continue . . .

Explanation

In the above program, we created a class Demo that contains the Main() method. Here we created an array of integers that contains negative and positive integer elements.

for (loop = 0; loop < arr.Length; loop++)
{
    if (arr[loop] < 0)
        arr[loop] = -arr[loop];
}

In the above code, we converted negative integer values into positive values, and then we printed the elements of the array on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.