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.
- Input size and array elements from user. Store it in some variable say
size
andarr
. - 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 likefor(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;
}
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 😉
Recommended posts
- Array and Matrix programming exercises index.
- C program to count even and odd elements in array.
- C program to count total number of duplicate elements in an array.
- C program to count frequeny of each array element.
- C program to delete all duplicate elements from an array.
- C program to insert element in array.