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

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

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.

Program:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.