C program to count total number of negative elements in array

Write a C program to read elements in an array and count total number of negative elements in array. C program to find all negative elements in an array. 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 C programming, If else, For loop, Array

Must know -

Logic to count total negative/positive elements in an 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.
Below is the step by step descriptive logic to count negative/positive elements in array.

  1. Input size and array elements from user. Store it in some variable say n and arr.
  2. To store count of negative elements, declare and initialize a variable with 0, say count = 0.
  3. Run a loop from 0 to n i.e. size of array. The loop structure should look like for(i=0; i<n; i++).
  4. Inside the loop check if the current number is negative, then increment the count by 1. Means perform if(arr[i] < 0) then, count = count + 1.
  5. Finally, after loop you are left with total negative element count.

Program to count total negative elements in an array

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

#include <stdio.h>

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

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


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

    /*
     * Counts total number of negative elements in array
     */
    for(i=0; i<n; i++)
    {
        /* Increment count if current array element is negative */
        if(arr[i]<0)
        {
            count++;
        }
    }

    printf("\nTotal number of negative elements = %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 number of negative elements = 5

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>