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.

Example:
If elements of array are: 10, -2, 5, -20, 1, 50, 60, -50, -12, -9
Total number of negative elements are: 5

Required knowledge:

Basic C programming, If else, For loop, Array

Before counting all negative element in array you must know how to check whether a number is negative or not.

Algorithm:

Step 1: Read elements in array.
Step 2: Set count=0.
Step 3: Set i=0.
Step 4: if array[i] < 0 then increment count by 1 i.e. count = count + 1
Step 5: Increment value of i by 1 i.e. i = i + 1.
Step 6: Repeat Step 4-5 till i<n.
Step 7: Print count.

Program:

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

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

    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++)
    {
        if(arr[i]<0)
        {
            count++;
        }
    }

    printf("\nTotal number of negative elements = %d", count);

    return 0;
} 
Output
X
_
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 ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment