In: Computer Science
Consider the following code:
void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void function(int arr[], int length)
{
for (int i = 0; i<length / 2; i++)
swap(arr, i, (length / 2 + i) % length);
}
If the input to the function was int arr[] = { 6, 1, 8, 2, 5, 4, 3, 7 }; function(arr,8); What values would be stored in the array after calling the function?
What is the output of the following code? (as always indicate "error" if there is any kind of runtime or compile-time error or "infinite" if there is an infinite loop)
void swap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}
void function(int arr[], int arr2[], int length)
{
for (int i = 0; i<length; i++)
{
swap(arr[i], arr[(i + arr2[i]) % length]);
}
}
int main()
{
int arr1[] = { 5, 2, 3, 7, 1, 6, 8, 4 };
int arr2[] = { 1, 4, -2, -1, 2, 7, 2, 1 };
function(arr1, arr2, 8);
for (int a : arr1)
cout << a << " ";
}
1) Values in the array after calling the function
Below is the program of the above output -
public class Main
{
static void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void function(int arr[], int length)
{
for (int i = 0; i<length / 2; i++)
swap(arr, i, (length / 2 + i) % length);
}
public static void main(String[] args) {
int arr[] = { 6, 1, 8, 2, 5, 4, 3, 7 };
function(arr,8);
for(int i=0;i<8;i++){
System.out.print(arr[i] + " ");
}
}
}
2) Improvised Code
#include<iostream>
using namespace std;
void swap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}
void function(int arr[], int arr2[], int length)
{
for (int i = 0; i<length; i++)
{
swap(arr[i], arr[(i + arr2[i]) % length]);
}
}
int main(){
int arr1[] = { 5, 2, 3, 7, 1, 6, 8, 4 };
int arr2[] = { 1, 4, -2, -1, 2, 7, 2, 1 };
function(arr1, arr2, 8);
for (int a : arr1){
cout<<a<<" ";
}
}
Output
Drop a comment for any update or clarification, I would love to assist you.