Q:

Rust program to swap adjacent elements of the array

belongs to collection: Rust Arrays Programs

0

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.

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 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.

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 find out the first repeated elemen... >>
<< Rust program to add two integer arrays...