Write a c program for Searching for an element
Write a c program for Searching for an element
Write a c program for Searching for an element
int arr[5] = {2, 4, 6, 8, 10};
Enter the number you want to search for: 6
The number 6 was found at index 2
#include <stdio.h>
int main() {
int arr[5] = {2, 4, 6, 8, 10};
int num, i, flag = 0;
printf("Enter the number you want to search for: ");
scanf("%d", &num);
for (i = 0; i < 5; i++) {
if (arr[i] == num) {
printf("The number %d was found at index %d\n", num, i);
flag = 1;
break;
}
}
if (flag == 0) {
printf("The number %d was not found in the array\n", num);
}
return 0;
}
Enter the number you want to search for: 8
The number 8 was found at index 3
This program initializes an array with 5 integers, then prompts the user to enter a number to search for. Using a for loop, the program checks each element of the array for a match with the user-entered number. If a match is found, the program prints the index of the match and sets a flag variable to 1. After the for loop, if the flag variable is still 0, the program prints that the number was not found in the array.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.