Q:

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

belongs to collection: Rust Arrays Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust Arrays Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to search an item into the array usin... >>
<< Rust program to print prime numbers from the array...