- Write a C program to print all negative numbers of an array.
- How to print all negative elements of an integer array in C.
Required Knowledge
- C printf and scanf functions
- For loop in C
- Arrays in C
Algorithm to print negative numbers of an array
Let inputArray is an integer array having N elements.
- Using a for loop, traverse inputArray from index 0 to N-1.
- For every element inputArray[i], check whether it is negative number or not(inputArray[i] < 0) and print it accordingly.
C program to print all negative elements of an array
#include <stdio.h> #include <conio.h> int main(){ int inputArray[100], elementCount, counter; printf("Enter Number of Elements in Array\n"); scanf("%d", &elementCount); printf("Enter %d numbers \n", elementCount); /* Read array elements */ for(counter = 0; counter < elementCount; counter++){ scanf("%d", &inputArray[counter]); } /* Iterate form index 0 to elementCount-1 and check for negative numbers */ printf("Negative Elements in Array\n"); for(counter = 0; counter < elementCount; counter++){ if(inputArray[counter] < 0) { printf("%d ", inputArray[counter]); } } getch(); return 0; }
Output
Enter Number of Elements in Array 8 Enter 8 numbers 2 -4 9 10 0 -5 -1 1 Negative Elements in Array -4 -5 -1