C# Program to Negate the Positive Elements of Array

«
»

This is a C# Program to negate the positive elements of array.

Problem Description

This C# Program Negates the Positive Elements of Array.

Problem Solution

The array elements are obtained from the user and the elements of the array are negated.

advertisement
Program/Source Code

Here is source code of the C# Program to Negate the Positive Elements of Array. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Negate the Positive Elements of Array
 */
using System;
using System.Collections.Generic;
using System.Text;
namespace program
{
    class negate
    {
        public static void Main()
        {
            int[] a = new int[10];
            Console.WriteLine("Enter 5 Elements : ");
            for (int i = 0; i < 5; i++)
            {
                a[i] = Convert.ToInt16(Console.ReadLine());
                if (a[i] > 0)
                    a[i] = -a[i];
            }
            Console.WriteLine("Elements:");
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(a[i]);
            }
            Console.ReadLine();
        }
    }
}
Program Explanation

This C# program, we are reading the value of 5 elements value using for loop and assign the value to ‘a[]’ array variable. If condition statement is used to check the value of ‘a[]’ variable is greater than 0. If the condition is true, then execute the statement. Assign the value of ‘a[]’ variable to the minus symbol of a[] variable. Hence using foreach loop print negate of positive elements of an array.

advertisement
Runtime Test Cases
 
Enter 5 Elements :
10
7
8
45
67
Elements :
-10
-7
-8
-45
-67

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn