Write a c program for Searching for an element
Data Structure Array (Article) Array (Program)
119
Given Input:
int arr[5] = {2, 4, 6, 8, 10};
Enter the number you want to search for: 6
Expected Output:
The number 6 was found at index 2
Program:
#include
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;
}
Output:
Enter the number you want to search for: 8
The number 8 was found at index 3
Explanation:
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.
This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.
The number 6 was found at index 2
Program:
#include 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; }
Output:
Enter the number you want to search for: 8 The number 8 was found at index 3
Explanation:
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.
This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.