Example:
Input array:
-1
-10
100
5
61
-2
-23
8
-90
51
Output: -1, -10, -2, -23, -90
Required knowledge
Basic C programming, If else, For loop, ArrayBefore you dive into this program, I recommend you to learn these concepts prior.
- How to input and display array elements using loop.
- How to check whether a number is negative or not.
Logic to display 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.Now, considering our case where we need to display only negative elements of array. Below is a descriptive logic to display all negative elements of array.
- Input elements in array.
- Check if the current element is negative or not. If the current array element is negative then print the current element otherwise skip. To check you simple use if(array[i] < 0) (where i is the current array index).
- Repeat step 2 till the last element of array.
Program to print negative elements in array
/** * C program to print all negative elements in array */ #include <stdio.h> #define MAX_SIZE 100 int main() { int arr[MAX_SIZE]; //Declares an array of MAX_SIZE int i, n; /* * 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]); } printf("\nAll negative elements in array are : "); for(i=0; i<n; i++) { //Print current element if it 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
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 ;)
You may also like
- 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.