Logic to count negative
Logic to count negative
In previous post we learned to print negative elements in array. Here for this problem
we will use same logic, but instead of printing negative elements we will count them.
i. Input size and array elements from user. Store it in some variable
say size and arr.
ii. Declare and initialize a variable count with zero, to store count of negative
elements.
iii. Iterate through each element in array, run a loop from 0 to size. Loop structure
should look like for(i=0; i<size; i++).
iv. Inside loop check if current number is negative, then increment count by 1.
v. Finally, after loop you are left with total negative element count.
#include <stdio.h>
int main()
{
int arr[MAX_SIZE]; // Declares array of size 100
int i, size, count = 0;
/*
* Count total negative elements in array
*/
for(i=0; i<size; i++)
{
/* Increment count if current array element is negative
*/
if(arr[i] < 0)
{
count++;
}
}
return 0;
}