Rust program to swap adjacent elements of the array

Rust | Array Sorting: Write a program to swap adjacent elements of the array.
Submitted by Nidhi, on October 22, 2021

Problem Solution:

In this program, we will create an array of integers then we will swap the adjacent elements of the array and print the updated array.

Program/Source Code:

The source code to swap adjacent elements of the array is given below. The given program is compiled and executed successfully.

// Rust program to swap adjacent elements 
// of the array

fn main() 
{
    let mut arr:[usize;6] = [0,1,2,3,4,5];
    let mut i:usize=0;
    let mut temp:usize=0;
    
    println!("Array before swapping: {:?}",arr);
    
    // Swap adjacent elements
    while i<=4
    {
        temp = arr[i];
        arr[i] = arr[i+1];
        arr[i+1] = temp;
        i = i + 2;
    }
    
    println!("Array after swapping: {:?}",arr);
}

Output:

Array before swapping: [0, 1, 2, 3, 4, 5]
Array after swapping: [1, 0, 3, 2, 5, 4]

Explanation:

Here, we created an array of integers with 6 elements, and then we swapped the adjacent elements of the array. After that, we printed the updated array.

Rust Arrays Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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