Question:
How to Swap ith element of the array with (i+2)th element using C++?

Summary:

Suppose we have an array of n positive integers. Our task is to swap every ith element of the array with (i+2)th element.


Solution:

//User function Template for C++


/*Function to swap array elements

* arr : array input

* n : number of elements in array

*/

class Solution{

  public:

    void swapElements(int arr[], int n){

        

        for(int i=0; i<n-2; i++){

            swap(arr[i], arr[i+2]);

        }

        

    }

};


Explanation:

This code is a C++ function template that defines a class Solution with a member function swapElements. This function swaps every alternate element of the array with the element two positions ahead of it. Here's a breakdown of the code:


  • class Solution{ ... };: This defines a class named Solution which encapsulates the solution for a problem.

  • public:: This keyword declares that the members following it will be accessible from outside the class.

  • void swapElements(int arr[], int n): This is a member function of the Solution class. It takes an integer array arr and its size n as input parameters.

  • for(int i=0; i<n-2; i++): This loop iterates over the array from index 0 to n-3 (since n-2 is used as the loop condition).

  • swap(arr[i], arr[i+2]): This function swaps the element at index i with the element at index i+2. It uses the swap function, which is a part of the C++ standard library and is used to swap two values.

So, in summary, this function swaps every alternate element of the array with the element two positions ahead of it, excluding the last two elements of the array.


Suggested blogs:

>Python Error Solved: load_associated_files do not load a txt file

>Python Error Solved: pg_config executable not found

>Set up Node.js & connect to a MongoDB Database Using Node.js

>Setting up a Cloud Composer environment: Step-by-step guide

>What is microservice architecture, and why is it better than monolithic architecture?

>What is pipe in Angular?

>What makes Python 'flow' with HTML nicely as compared to PHP?

>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?

>Creating custom required rule - Laravel validation

>How to configure transfers for different accounts in stripe with laravel?


Ritu Singh

Ritu Singh

Submit
0 Answers