Swap two elements in an array with code

CODE: 

  1. #include<stdio.h>
  2. int main()
  3. {
  4.     int i1,i2;
  5.     int n;    
  6.    
  7.     printf("Enter the size of array: \n");
  8.     scanf("%d", &n);
  9.     int arr[n];
  10.     for (int i = 0; i < n; i++)
  11.     {
  12.         printf("Enter element with %d : ", i);
  13.         scanf("%d", &arr[i]);
  14.     }
  15.     printf("Enter two index you want to swap: \n");

  16.     scanf("%d %d", &i1, &i2);

  17.  
  18.    for (int i = 0; i < n; i++)
  19.     {
  20.        for (int j = 0; j < n; j++)
  21.        {
  22.            if (i==i1 && j==i2)
  23.            {
  24.                int temp=arr[i];
  25.                    arr[i]=arr[j];
  26.                    arr[j]=temp;
  27.            }  
  28.        }
  29.     }
  30.     printf("After swapping the two elements, the array is like this: \n");
  31.     for (int i = 0; i < n; i++)
  32.     {
  33.         printf("%d ---------> %d\n", i, arr[i]);
  34.     }
  35.     return 0;
  36. }

OUTPUT:

Enter the size of array:
4
Enter element with 0 : 1
Enter element with 1 : 3
Enter element with 2 : 5
Enter element with 3 : 7
Enter two index you want to swap:
1
3
After swapping the two elements, the array is like this:
0 ---------> 1
1 ---------> 7
2 ---------> 5
3 ---------> 3
Post a Comment (0)
Previous Post Next Post