C# Sharp Exercises: Count positive and negative numbers in a given array of integers
C# Sharp Basic: Exercise-89 with Solution
Write a C# Sharp program to count positive and negative numbers in a given array of integers.
Sample Solution:
C# Sharp Code:
using System;
using System.Linq;
namespace exercises
{
class Program
{
static void Main(string[] args)
{
int[] nums = { 10, -11, 12, -13, 14, -18, 19, -20 };
Console.WriteLine("Original Array elements:");
foreach (var item in nums)
{
Console.Write(item.ToString() + " ");
}
Console.WriteLine(test(nums));
int[] nums1 = { -4,-3,-2,0,3,5,6,2,6};
Console.WriteLine("\nOriginal Array elements:");
foreach (var item in nums1)
{
Console.Write(item.ToString() + " ");
}
Console.WriteLine(test(nums1));
int[] nums2 = {};
Console.WriteLine("\nOriginal Array elements:");
foreach (var item in nums2)
{
Console.Write(item.ToString() + " ");
}
Console.WriteLine(test(nums2));
}
public static string test(int[] nums)
{
var pos = nums.Where(n => n > 0);
var neg = nums.Where(n => n < 0);
return "\nNumber of positive numbers: " + pos.Count() + "\nNumber of negative numbers: " + neg.Count();
}
}
}
Sample Output:
Original Array elements: 10 -11 12 -13 14 -18 19 -20 Number of positive numbers: 4 Number of negative numbers: 4 Original Array elements: -4 -3 -2 0 3 5 6 2 6 Number of positive numbers: 5 Number of negative numbers: 3 Original Array elements: Number of positive numbers: 0 Number of negative numbers: 0
Flowchart:
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to find the sum of the interior angles (in degrees) of a given Polygon. Input number of straight line(s).
Next: Write a C# Sharp program to count number of ones and zeros in the binary representation of a given integer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework