Complementary task for topic: 3
M Nemeth · 2023-08-29 15:21:04.615220'
Arrays: search
Arrays: search
Write a C program that searches for a specific element (from the user) in an integer array {5, 10, 15, 20, 25, 30, 35} and displays whether it is found or not.
Hint: Traverse on the table search for the equality
Solution
#include
int main() {
int numbers[7] = {5, 10, 15, 20, 25, 30, 35}; // Initialize the array with values
int target;
int found = 0;
printf("Enter the number to search for: ");
scanf("%d", &target);
for (int i = 0; i < 7; i++) {
if (numbers[i] == target) {
found = 1;
break;
}
}
if (found) {
printf("Number %d is found in the array.\n", target);
} else {
printf("Number %d is not found in the array.\n", target);
}
return 0;
}
Explanation
In this example, there are a few new elements. First is to use a flag, which is now the found variable. Flag variable is used, when we want to change the behavior after the loop is over. Second is the usage of the break that will jump out from the loop immadiately. Without this the program also works properly. It is adisable to avoid the use of break; and continue; etc. How to avoid the usage? for (int i = 0; i < 7&&!found; i++) !found: read: "not found "the negate of the flag, the is zero (=false) while one target is not found. So that will work properly as well.