Write a program to search an element in a given list of values

Python Program to Search an Element in a List



This article deals with some programs in Python that searches an element in a list. Here both element and list must be entered by user at run-time. Here are the list of programs covered in this article:

  • Search an element in a list of 5 elements
  • Search an element in a list of n elements
  • Check if a value exists in a given list, using in operator

Write a program to search an element is a given list of values

Previous
Next

Linear Search:

Linear search is one of searching algorithms to find an element in array. Linear search can apply on random array also. In linear search, every time index element compare with the element to be searched. If element found, it returns the index value as location. If element not found, it display error message.

#include int main() { int a[30], m, key, i, n, found=0; printf("Enter size of array : "); scanf("%d",&m); printf("Enter Elements in array : \n"); for(i=0; i
Previous
Next

C Program To Search An Element In An Array | C Programs

in C Programs Comments Off on C Program To Search An Element In An Array | C Programs

C Program to search for an element in an array – In this article, we will detail in on the various methods to search for an element in an array in C programming.

  • C Program Find Circumference Of A Circle | 3 Ways
  • C Program Area Of Trapezium – 3 Ways | C Programs

Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.

The means used in this specific piece are as follows:

  • Using Standard Method
  • Using Function
  • Using Recursion

As we all know, an array is a collection or sequential arrangement of elements in any given order. Arrays form the basics of the C programming language.

Write a program to search an element in a given list of values

As you can see in the photo uploaded above, the elements are first entered in no particular order.

The elements entered here are 4, 6, 2, 1 and 3.

The target element is mentioned here as well. The target element here is 2.

Once the element is present in the array, it will say “element found”.

Thus, the several methods to find an element in an array are as follows:

Search an Element in Array using C

// linear search #include int main() { int a[100], n, element, pos=0; int i; printf("Enter array size [1-100]: "); scanf("%d", &n); printf("Enter array elements: "); for(i=0; iOutput for the different test-cases:-

Enter array size [1-100]: 5
Enter array elements: 5 20 9 85 4
Enter element to search: 20
20 found at position 2

Enter array size [1-100]: 3
Enter array elements: 9 5 1
Enter element to search: 8
8 not found.

Enter array size [1-100]: 6
Enter array elements:1 2 1 2 3 1
Enter element to search: 2
2 found at position 2

To find an element in the array we use for loop, if statement and equality operator. If the array element is equal to the searching element then it will be displayed with position and program completed because of return 0; next lines does not execute. But if element not found then if condition not executed and statements after for loop also executed.

In the last input/output example we can observe that there is more than one element but our program display only first position. We can also write a program where we can search position of nth times occurred element in the array.

Search an element in a Linked List (Iterative and Recursive)

Write a function that searches a given key ‘x’ in a given singly linked list. The function should return true if x is present in linked list and false otherwise.

bool search(Node *head, int x)

For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then function should return false. If key to be searched is 14, then the function should return true.
Iterative Solution

1) Initialize a node pointer, current = head. 2) Do following while current is not NULL a) current->key is equal to the key being searched return true. b) current = current->next 3) Return false

Following is iterative implementation of above algorithm to search a given key.




// Iterative C++ program to search
// an element in linked list
#include
using namespace std;
/* Link list node */
class Node
{
public:
int key;
Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_key)
{
/* allocate node */
Node* new_node = new Node();
/* put in the key */
new_node->key = new_key;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Checks whether the value x is present in linked list */
bool search(Node* head, int x)
{
Node* current = head; // Initialize current
while (current != NULL)
{
if (current->key == x)
return true;
current = current->next;
}
return false;
}
/* Driver program to test count function*/
int main()
{
/* Start with the empty list */
Node* head = NULL;
int x = 21;
/* Use push() to construct below list
14->21->11->30->10 */
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);
search(head, 21)? cout<<"Yes" : cout<<"No";
return 0;
}
// This is code is contributed by rathbhupendra




// Iterative C program to search an element in linked list
#include
#include
#include
/* Link list node */
struct Node
{
int key;
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_key)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the key */
new_node->key = new_key;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Checks whether the value x is present in linked list */
bool search(struct Node* head, int x)
{
struct Node* current = head; // Initialize current
while (current != NULL)
{
if (current->key == x)
return true;
current = current->next;
}
return false;
}
/* Driver program to test count function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
int x = 21;
/* Use push() to construct below list
14->21->11->30->10 */
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);
search(head, 21)? printf("Yes") : printf("No");
return 0;
}




// Iterative Java program to search an element
// in linked list
//Node class
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
//Linked list class
class LinkedList
{
Node head; //Head of list
//Inserts a new node at the front of the list
public void push(int new_data)
{
//Allocate new node and putting data
Node new_node = new Node(new_data);
//Make next of new node as head
new_node.next = head;
//Move the head to point to new Node
head = new_node;
}
//Checks whether the value x is present in linked list
public boolean search(Node head, int x)
{
Node current = head; //Initialize current
while (current != null)
{
if (current.data == x)
return true; //data found
current = current.next;
}
return false; //data not found
}
//Driver function to test the above functions
public static void main(String args[])
{
//Start with the empty list
LinkedList llist = new LinkedList();
/*Use push() to construct below list
14->21->11->30->10 */
llist.push(10);
llist.push(30);
llist.push(11);
llist.push(21);
llist.push(14);
if (llist.search(llist.head, 21))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Pratik Agarwal




# Iterative Python program to search an element
# in linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class
class LinkedList:
def __init__(self):
self.head = None # Initialize head as None
# This function insert a new node at the
# beginning of the linked list
def push(self, new_data):
# Create a new Node
new_node = Node(new_data)
# 3. Make next of new Node as head
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
# This Function checks whether the value
# x present in the linked list
def search(self, x):
# Initialize current to head
current = self.head
# loop till current not equal to None
while current != None:
if current.data == x:
return True # data found
current = current.next
return False # Data Not found
# Code execution starts here
if __name__ == '__main__':
# Start with the empty list
llist = LinkedList()
''' Use push() to construct below list
14->21->11->30->10 '''
llist.push(10);
llist.push(30);
llist.push(11);
llist.push(21);
llist.push(14);
if llist.search(21):
print("Yes")
else:
print("No")
# This code is contributed by Ravi Shankar




// Iterative C# program to search an element
// in linked list
using System;
// Node class
public class Node
{
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
}
// Linked list class
public class LinkedList
{
Node head; // Head of list
// Inserts a new node at the front of the list
public void push(int new_data)
{
// Allocate new node and putting data
Node new_node = new Node(new_data);
// Make next of new node as head
new_node.next = head;
// Move the head to point to new Node
head = new_node;
}
// Checks whether the value x is present in linked list
public bool search(Node head, int x)
{
Node current = head; // Initialize current
while (current != null)
{
if (current.data == x)
return true; // data found
current = current.next;
}
return false; // data not found
}
// Driver code
public static void Main(String []args)
{
// Start with the empty list
LinkedList llist = new LinkedList();
/*Use push() to construct below list
14->21->11->30->10 */
llist.push(10);
llist.push(30);
llist.push(11);
llist.push(21);
llist.push(14);
if (llist.search(llist.head, 21))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code contributed by Rajput-Ji




Output:



Yes

Recursive Solution

bool search(head, x) 1) If head is NULL, return false. 2) If head's key is same as x, return true; 3) Else return search(head->next, x)

Following is the recursive implementation of the above algorithm to search a given key.




// Recursive C++ program to search
// an element in linked list
#include
using namespace std;
/* Link list node */
struct Node
{
int key;
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_key)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the key */
new_node->key = new_key;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Checks whether the value x is present in linked list */
bool search(struct Node* head, int x)
{
// Base case
if (head == NULL)
return false;
// If key is present in current node, return true
if (head->key == x)
return true;
// Recur for remaining list
return search(head->next, x);
}
/* Driver code*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
int x = 21;
/* Use push() to construct below list
14->21->11->30->10 */
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);
search(head, 21)? cout << "Yes" : cout << "No";
return 0;
}
// This code is contributed by SHUBHAMSINGH10




// Recursive C program to search an element in linked list
#include
#include
#include
/* Link list node */
struct Node
{
int key;
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_key)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the key */
new_node->key = new_key;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Checks whether the value x is present in linked list */
bool search(struct Node* head, int x)
{
// Base case
if (head == NULL)
return false;
// If key is present in current node, return true
if (head->key == x)
return true;
// Recur for remaining list
return search(head->next, x);
}
/* Driver program to test count function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
int x = 21;
/* Use push() to construct below list
14->21->11->30->10 */
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);
search(head, 21)? printf("Yes") : printf("No");
return 0;
}




// Recursive Java program to search an element
// in linked list
// Node class
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
// Linked list class
class LinkedList
{
Node head; //Head of list
//Inserts a new node at the front of the list
public void push(int new_data)
{
//Allocate new node and putting data
Node new_node = new Node(new_data);
//Make next of new node as head
new_node.next = head;
//Move the head to point to new Node
head = new_node;
}
// Checks whether the value x is present
// in linked list
public boolean search(Node head, int x)
{
// Base case
if (head == null)
return false;
// If key is present in current node,
// return true
if (head.data == x)
return true;
// Recur for remaining list
return search(head.next, x);
}
// Driver function to test the above functions
public static void main(String args[])
{
// Start with the empty list
LinkedList llist = new LinkedList();
/* Use push() to construct below list
14->21->11->30->10 */
llist.push(10);
llist.push(30);
llist.push(11);
llist.push(21);
llist.push(14);
if (llist.search(llist.head, 21))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Pratik Agarwal




# Recursive Python program to
# search an element in linked list
# Node class
class Node:
# Function to initialise
# the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
class LinkedList:
def __init__(self):
self.head = None # Initialize head as None
# This function insert a new node at
# the beginning of the linked list
def push(self, new_data):
# Create a new Node
new_node = Node(new_data)
# Make next of new Node as head
new_node.next = self.head
# Move the head to
# point to new Node
self.head = new_node
# Checks whether the value key
# is present in linked list
def search(self, li, key):
# Base case
if(not li):
return False
# If key is present in
# current node, return true
if(li.data == key):
return True
# Recur for remaining list
return self.search(li.next, key)
# Driver Code
if __name__=='__main__':
li = LinkedList()
li.push(1)
li.push(2)
li.push(3)
li.push(4)
key = 4
if li.search(li.head,key):
print("Yes")
else:
print("No")
# This code is contributed
# by Manoj Sharma




// Recursive C# program to search
// an element in linked list
using System;
// Node class
public class Node
{
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
}
// Linked list class
public class LinkedList
{
Node head; //Head of list
//Inserts a new node at the front of the list
public void push(int new_data)
{
//Allocate new node and putting data
Node new_node = new Node(new_data);
//Make next of new node as head
new_node.next = head;
//Move the head to point to new Node
head = new_node;
}
// Checks whether the value x is present
// in linked list
public bool search(Node head, int x)
{
// Base case
if (head == null)
return false;
// If key is present in current node,
// return true
if (head.data == x)
return true;
// Recur for remaining list
return search(head.next, x);
}
// Driver code
public static void Main()
{
// Start with the empty list
LinkedList llist = new LinkedList();
/* Use push() to construct below list
14->21->11->30->10 */
llist.push(10);
llist.push(30);
llist.push(11);
llist.push(21);
llist.push(14);
if (llist.search(llist.head, 21))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by PrinciRaj1992




Output:

Yes

This article is contributed by Ravi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Write a program to search an element in a given list of values




Article Tags :
Linked List
Practice Tags :
Linked List