C++ Program to Count Positive and Negative Numbers in an ArrayIn this post, we will count the number of positive integers, negative numbers, and zeroes in an array. To evaluate whether a number is positive, negative, or zero, the if-else statement will be applied. We will be using C++. In the following code, we initially prompt the user to input the number of array elements to be stored in the count variable. Next we ask user to input array elements and retain in an integer array "input". Using a for loop, we scan the input array from index 0 to count-1 and examine each array element to determine whether it is positive, negative, or zero. To count the number of positive, negative, and zero values, we use the variables nCount, pCount, and zCount. Finally, we use cout to output the number of zeroes, positive and negative values on the display. C++ Program: Output Enter Number of Elements in Array 8 Enter 8 numbers -65 12 -5 6 0 -22 0 38 Negative Numbers : 3 Positive Numbers : 3 Zeroes : 2 Time complexity will be O(n). Auxiliary space will be O(1). By Using Recursion MethodC++ Program: Output Array: -9 7 -5 3 2 Count of Positive elements = 3, Count of Negative elements = 2 Time complexity will be O(n). Auxiliary space will be O(n). Alternative method utilizing the C++ Standard Template Library (STL) and the 'count_if()'function:C++ Program: Output Array: -9 7 -5 3 2 Count of Positive elements = 3, Count of Negative elements = 2 Time complexity will be O(n). Auxiliary space will be O(n). |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India