Rust program to search an item into the array using linear search

Rust | Array Example: Write a program to search an item into the array using linear search.
Submitted by Nidhi, on October 21, 2021

Problem Solution:

In this program, we will create an array of integer elements then we will read an item from the user and search the item into the array using linear or sequential search technique.

Program/Source Code:

The source code to search an item into the array using linear search is given below. The given program is compiled and executed successfully.

// Rust program to search an item into 
// the array using linear search

use std::io;

fn main() 
{
    let mut arr:[usize;5] = [1,5,11,26,23];
    let mut flag:i32 = 0;
    
    let mut i:usize = 0;
    
    let mut item:usize = 0;
    let mut input = String::new();
    
    println!("Enter Item: ");
    io::stdin().read_line(&mut input).expect("Not a valid string");
    item = input.trim().parse().expect("Not a valid number");
    
    while i<5
    {
        if item == arr[i] {
            flag = 1;
            println!("Item {0} found at index {1}", item, i);
            break;
        }
        i=i+1;
    }
        
    if flag == 0 {
        println!("Item {} not found in array",item);
    }
}

Output:

Enter Item: 
11
Item 11 found at index 2

Explanation:

Here, we created an array of the integer with 5 elements, and then we read the item from the user.

After that, we searched the item into the array using the linear search technique and print the index of the item into the array.

Rust Arrays Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.