Array Exercises
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.
Required knowledge
Basic C programming, If else, c-Arrays, C Loops
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.
- Input size and array elements from user. Store it in some variable say size and arr.
- Declare and initialize a variable count with zero, to store count of negative elements.
- Iterate through each element in array, run a loop from 0 to size. Loop structure should look like for(i=0; i<size; i++).
- Inside loop check if current number is negative, then increment count by 1.
- 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; }