Problem Statement:
You are given a positive integer n .The second line will contain n positive integers.And the third line will contain a value Q.The next line will contain Q queries,every query will contain two values L and R.Now,You need to swap two values by the following way-
>> Swap the values of index L with R .
And lastly print the modified array.
Note - You must swap the values using a function with pointers.And Consider the array as 1 base index.
See the sample input output for more clarification.
Constraints-
2<=n<=100
Values of array will be given between 1-1000
1<=L,R<=100 and L!=R
Sample Input : Sample Output :
7
9 1 17 3 5 2 7
4 17 3 5 2 9 1 7
1 3
2 4
5 3
4 6
Explanation -
1st query - swap 1st index value with 3rd index value then the array will be - 17 1 9 3 5 2 7
answer:
Here is a function in C that swaps the values of two variables using pointers:
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
This function takes two pointers a
and b
, and swaps the values of the variables they point to using a temporary variable.
To use this function to swap the values of two elements in an array, you can do the following:
int arr[] = {9, 1, 17, 3, 5, 2, 7};
int n = 7;
// Swap elements at indices 1 and 3
swap(&arr[1], &arr[3]);
// Print the modified array
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
This will output 17 3 9 1 5 2 7
.
To implement the required behavior, you can read the values of n
, the array, and Q
from the input, and then read Q
pairs of values L
and R
. For each pair, you can call the swap
function to swap the values at indices L
and R
in the array, and then print the modified array.
Here is the complete program:
#include <stdio.h>
// Function prototype
void swap(int *a, int *b);
int main(void) {
// Read the size of the array
int n;
scanf("%d", &n);
// Read the elements of the array
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Read the number of queries
int q;
scanf("%d", &q);
// Read and process each query
for (int i = 0; i < q; i++) {
// Read the indices to swap
int l, r;
scanf("%d %d", &l, &r);
// Swap the values at indices l and r
swap(&arr[l - 1], &arr[r - 1]);
// Print the modified array
for (int j = 0; j < n; j++) {
0 Comments