C program to print all negative elements in an array

Previous Program Next Pattern
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.

Input array:
Output: -1, -10, -2, -23, -90

Required knowledge

Basic C programming, If else, For loop, Array

Before you dive into this program, I recommend you to learn these concepts prior.

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.
Let's now implement this.

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;

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 ;)

Previous Program Next Pattern
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment