समस्या
उपयोगकर्ता द्वारा रनटाइम पर सरणी से एक तत्व खोजने के लिए एक C प्रोग्राम लिखें और खोज के बाद परिणाम स्क्रीन पर प्रदर्शित किया जाए। यदि खोजा जाने वाला तत्व सरणी में नहीं है तो, हमें "search element is not found" प्रदर्शित करना होगा।
समाधान
एक सरणी का उपयोग सामान्य तत्वों के समूह को एक नाम के तहत रखने के लिए किया जाता है।
सरणी ऑपरेशन निम्नानुसार हैं:
- इंसर्ट
- डिलीट
- सर्च
एल्गोरिथम
पॉइंटर्स की मदद से सरणी में तत्वों को खोजने के लिए एक एल्गोरिथम देखें:
चरण 1 - तत्वों की संख्या डिक्लेयर और पढ़ें।
चरण 2 - रनटाइम पर सरणी आकार डिक्लेयर और पढ़ें।
चरण 3 - सरणी तत्वों को इनपुट करें।
चरण 4 - एक पॉइंटर वेरिएबल डिक्लेयर करें।
चरण 5 - रनटाइम पर डायनामिकली मेमोरी एलोकेट करें।
चरण 6 - वह तत्व दर्ज करें जिसे खोजा जाना है।
चरण 7 - ट्रैवर्स करके जांचें कि क्या कोई तत्व सरणी में मौजूद है। यदि तत्व मिलता है तो "Yes" प्रदर्शित करें, अन्यथा "No"।
उदाहरण
सरणी का आकार है: 5
सरणी तत्व निम्नानुसार हैं:
1 2 3 4 5
खोजे जाने वाले तत्व दर्ज करें: 4
आउटपुट निम्नानुसार है:
4 is present in the array
उदाहरण
निम्नलिखित C प्रोग्राम पॉइंटर्स की मदद से सरणी में तत्वों को खोजता है:
#include <stdio.h>
int i, l;
int search(int, int*, int);
int main(){
int n, m;
printf("enter the size of array:");
scanf("%d", &n);
int a[n];
printf("enter the elements:\n");
for(i = 0; i < n; i++){
scanf("%d", &a[i]);
}
printf("enter the element to be searched:");
scanf("%d", &m);
search(n, a, m);
return 0;
}
int search(int n, int *a, int m){
for(i = 0; i < n; i++){
if(m == a[i]){
l = 1;
break;
}
}
if(l == 1){
printf("%d is present in the array", m);
}else{
printf("%d is not present in the array", m);
}
}
आउटपुट
Run 1: enter the size of array: 5 enter the elements: 14 12 11 45 23 enter the element to be searched: 11 11 is present in the array Run 2: enter the size of array: 3 enter the elements: 12 13 14 enter the element to be searched: 45 45 is not present in the array