C program to count negative elements in array

Write a C program to input elements in array and count negative elements in array. C program to find all negative elements in array. How to count negative elements in array using loop in C programming. Logic to count total negative elements in an array in C program.

Example

Input

Input array elements : 10, -2, 5, -20, 1, 50, 60, -50, -12, -9

Output

Total number of negative elements: 5

Required knowledge

Basic Input Output, If else, For loop, Array

Logic to count negative/positive elements in array

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.

Step by step descriptive logic to count negative elements in array.

  1. Input size and array elements from user. Store it in some variable say size and arr.
  2. Declare and initialize a variable count with zero, to store count of negative elements.
  3. Iterate through each element in array, run a loop from 0 to size. Loop structure should look like for(i=0; i<size; i++).
  4. Inside loop check if current number is negative, then increment count by 1.
  5. Finally, after loop you are left with total negative element count.

Program to count negative elements in array

/**
 * C program to count total number of negative elements in array
 */

#include <stdio.h>

#define MAX_SIZE 100    // Maximum array size


int main()
{
    int arr[MAX_SIZE];  // Declares array of size 100
    int i, size, count = 0;

    /* Input size of array */
    printf("Enter size of the array : ");
    scanf("%d", &size);


    /* Input array elements */
    printf("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    /*
     * 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++;
        }
    }

    printf("\nTotal negative elements in array = %d", count);

    return 0;
}

Output

Enter size of the array : 10
Enter elements in array : 10 -2 5 -20 1 50 60 -50 -12 -9

Total negative elements in array = 5

Happy coding 😉