ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.