Write a C program to input elements in array and print all negative elements. How to display all negative elements in array using loop in C program. Logic to display all negative elements in a given array in C programming.
Example
Input
Input array: -1 -10 100 5 61 -2 -23 8 -90 51
Output
Output: -1, -10, -2, -23, -90
Required knowledge
Basic C programming, If statement, For loop, Array
Logic to print negative elements in array
Displaying negative, positive, prime, even, odd or any special number doesn’t requires special skills. You only need to know how to display array elements and how to check that special number.
Step by step descriptive logic to display all negative elements in array.
- Declare and input elements in array.
- Run a loop from 0 to
N-1
(where N is array size). The loop structure should look likefor(i=0; i<N; i++)
. - For each element in array, if current element is negative i.e.
if(array[i] < 0)
then print it.
Program to print negative elements in array
/**
* C program to print all negative elements in array
*/
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE]; // Declare array of MAX_SIZE
int i, N;
/* Input size of the array */
printf("Enter size of the array : ");
scanf("%d", &N);
/* Input elements in the array */
printf("Enter elements in array : ");
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}
printf("\nAll negative elements in array are : ");
for(i=0; i<N; i++)
{
/* If current array element is negative */
if(arr[i] < 0)
{
printf("%d\t", arr[i]);
}
}
return 0;
}
Output
Enter size of the array : 10 Enter elements in array : -1 -10 100 5 61 -2 -23 8 -90 51 All negative elements in array are : -1 -10 -2 -23 -90
Happy coding 😉
Recommended posts
- Array and Matrix programming exercises index.
- C program to count total number of negative elements in an array.
- C program to count total number of even and odd elements in an array.
- C program to find sum of all array elements.
- C program to find maximum and minimum element in array.
- C program to print all unique elements in an array.