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, ArrayBefore 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
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
Enter elements in array : 10 -2 5 -20 1 50 60 -50 -12 -9
Total number of negative elements = 5
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to print all negative elements in an array.
- C program to read and print elements in an array.
- C program to count total number of duplicate elements in an array.
- C program to delete all duplicate elements from an array.
- C program to merge two array in a single array.
- C program to find reverse of an array.
- C program to count frequency of each element in an array.
- C program to search an element in an array.
- C program to sort elements of array in descending order.
- C program to find sum of all natural numbers from 1 to n.
- C program to print Fibonacci series up to n terms.
- C program to add two matrices.
- C program to subtract two matrices.
- C program to multiply two matrices.
- C program to perform scalar multiplication of matrix.
- C program to find transpose of a matrix.