To filter elements of an array based on a condition in C, you can use loops along with conditional statements.
In this example,
numbers
containing integers.evenNumbers
.#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int evenNumbers[10];
int evenIndex = 0;
for (int i = 0; i < 10; i++) {
if (numbers[i] % 2 == 0) {
evenNumbers[evenIndex++] = numbers[i];
}
}
printf("Even Numbers: ");
for (int i = 0; i < evenIndex; i++) {
printf("%d ", evenNumbers[i]);
}
return 0;
}
Even Numbers: 2 4 6 8 10
In this example,
words
containing strings.filteredWords
.#include <stdio.h>
#include <string.h>
int main() {
char *words[] = {"apple", "banana", "cherry", "date", "fig"};
char *filteredWords[5];
int filteredIndex = 0;
for (int i = 0; i < 5; i++) {
if (strlen(words[i]) > 5) {
filteredWords[filteredIndex++] = words[i];
}
}
printf("Filtered Words: ");
for (int i = 0; i < filteredIndex; i++) {
printf("%s ", filteredWords[i]);
}
return 0;
}
Filtered Words: banana cherry
In this tutorial, we learned How to Filter Elements of an Array based on a Condition in C language with well detailed examples.