What will be the output of the following code? [code] #include <bits/stdc++.h> using namespace std; void func1(int arr[], int left, int

What will be the output of the following code?
Code:
#include <bits/stdc++.h> 
using namespace std; 
void func1(int arr[], int left, int right) 
{ 
	while (left < right) 
	{ 
		int temp = arr[left]; 
		arr[left] = arr[right]; 
		arr[right] = temp; 
		left++; 
		right--; 
	} 
} 
void func(int arr[], int d, int n) 
{ 
	func1(arr, 0, d-1); 
	func1(arr, d, n-1); 
	func1(arr, 0, n-1); 
} 
void printArray(int arr[], int size) 
{ 
	for (int i = 0; i < size; i++) 
	cout << arr[i] << " "; 
} 
int main() 
{ 
	int arr[] = {1, 2, 3, 4, 5}; 
	int n = sizeof(arr)/sizeof(arr[0]); 
	int d = 2; 
	func(arr, d, n); 
	printArray(arr, n); 
	return 0; 
}
A. 3 2 1 4 5
B. 3 4 5 1 2
C. 5 4 3 2 1
D. error
 
Answer: b
Explanation: The given code rotates the input array by 2. It does so by applying a reversal algorithm to different segments of the array. First d elements and the rest of the array is reversed individually. Then the whole array is reversed which gives us the desired rotated array. So the output will be 3 4 5 1 2.
 

Tìm kiếm

Back
Top