C program to print all negative elements in an array

Write a C program to read elements in an array and print all negative elements. How to display all negative elements in an array using loop in C programming. Logic to display all negative elements in of a given array using loop.

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 else, For loop, Array

Must know -

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.

  1. Input elements in array.
  2. 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).
  3. 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;

    /* 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++)
    {
        // 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

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>