Pointer Assignment 15 — Swap Two Elements in an Array Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Swap Two Elements in an Array Using Pointers — Exchanging Values Through Addresses

📑 On this page:
  • How Pointer-Based Swapping Works
  • The Three Steps of Swapping
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to swap two elements of an array using a function
  • Why the addresses of array elements must be passed using &arr[i] and &arr[j]
  • How to modify original array values using pointer dereferencing
  • Why a temporary variable is required during swapping
  • How pointer parameters allow a function to change variables in the caller
  • How to validate array indexes before swapping

How Pointer-Based Swapping Works

Swapping means exchanging the values stored at two memory locations. In an array, each element has its own address. To swap arr[i] and arr[j], the program must exchange the values stored at &arr[i] and &arr[j].

A normal function cannot permanently change the caller's variables if it receives only their values, because C passes arguments by value. To change the original array elements, the function must receive their addresses. Pointer parameters such as int *a and int *b store those addresses, and *a and *b access the actual values stored there.

The swapping process uses a temporary variable. First, the value at the first address is saved in temp. Then the value at the second address is copied into the first location. Finally, the temporary value is copied into the second location. After these three assignments, the two array elements are exchanged.

💡 In one line: Pass the addresses of two array elements to a swap function, then exchange their values using temp = *a, *a = *b, and *b = temp.

Diagram showing two array elements being swapped using pointers and a temporary variable

The Three Steps of Swapping

Step Pointer operation Effect
1. Pass element addressesswap(&arr[i], &arr[j]);The function receives the memory addresses of the two elements
2. Save the first valueint temp = *a;The original value of the first element is stored safely
3. Exchange the values*a = *b; and *b = temp;The second value moves to the first location and the saved value moves to the second location

The temporary variable is essential. If you directly write *a = *b; followed by *b = *a;, both locations will end up with the same value, because the original value of *a would already be lost after the first assignment.

Pointer-based swapping is widely used in sorting algorithms such as bubble sort, selection sort, and quicksort. In those algorithms, two array elements are repeatedly exchanged until the entire array becomes sorted.

Complete C Program

Program: swap two elements in an array using pointers

#include <stdio.h>

#define MAX 100

/* Swap two integers using pointers. */
void swap(int *a, int *b) {
    int temp;

    temp = *a;   /* save the value at the first address */
    *a = *b;     /* copy the second value to the first address */
    *b = temp;   /* copy the saved value to the second address */
}

/* Swap two elements of an array by index. */
void swap_array_elements(int arr[], int i, int j) {
    if (i < 0 || j < 0 || i >= MAX || j >= MAX || i == j) {
        printf("Invalid indexes. No swap performed.\n");
        return;
    }

    swap(&arr[i], &arr[j]);
}

int main(void) {
    int arr[MAX];
    int n, i, j, k;

    printf("How many elements? ");
    if (scanf("%d", &n) != 1 || n <= 0 || n > MAX) {
        printf("Invalid size.\n");
        return 1;
    }

    printf("Enter %d integers:\n", n);
    for (k = 0; k < n; k++) {
        if (scanf("%d", &arr[k]) != 1) {
            printf("Invalid input.\n");
            return 1;
        }
    }

    printf("Enter the first index to swap: ");
    if (scanf("%d", &i) != 1 || i < 0 || i >= n) {
        printf("Invalid first index.\n");
        return 1;
    }

    printf("Enter the second index to swap: ");
    if (scanf("%d", &j) != 1 || j < 0 || j >= n) {
        printf("Invalid second index.\n");
        return 1;
    }

    printf("\nArray before swapping:\n");
    for (k = 0; k < n; k++) {
        printf("%d ", arr[k]);
    }
    printf("\n");

    swap_array_elements(arr, i, j);

    printf("\nArray after swapping:\n");
    for (k = 0; k < n; k++) {
        printf("%d ", arr[k]);
    }
    printf("\n");

    return 0;
}
                                    

Program Output

How many elements? 5
Enter 5 integers:
10 20 30 40 50
Enter the first index to swap: 1
Enter the second index to swap: 3

Array before swapping:
10 20 30 40 50 

Array after swapping:
10 40 30 20 50 
                                

A second run, where the same index is entered twice:

How many elements? 5
Enter 5 integers:
10 20 30 40 50
Enter the first index to swap: 2
Enter the second index to swap: 2

Invalid indexes. No swap performed.

Array before swapping:
10 20 30 40 50 

Array after swapping:
10 20 30 40 50 
                                

In the first run, the elements at index 1 and index 3 are exchanged. The value 20 moves to index 3, and the value 40 moves to index 1. In the second run, both indexes are the same, so the program reports that no swap is needed and the array remains unchanged.

Step-by-Step Explanation

Let us understand how the swap function changes the original array.

1. The swap function signature

void swap(int *a, int *b) receives two integer pointers. These pointers hold the addresses of the two array elements that need to be exchanged. The return type is void because the function does not return a value; it modifies the original memory locations directly.

2. Passing addresses from main

The call swap(&arr[i], &arr[j]); sends the addresses of the two required elements. The address-of operator & is necessary because the function must know where the values are stored in memory. Without addresses, the function would receive only copies of the values and could not change the original array.

3. Saving the first value

Inside the function, temp = *a; reads the value stored at the address held by a and saves it in temp. For example, if *a is 20, then temp becomes 20.

4. Copying the second value

*a = *b; copies the value stored at the address held by b into the location pointed to by a. If *b is 40, then the first element becomes 40.

5. Restoring the saved value

*b = temp; copies the saved value back into the second location. Since temp contains the original first value, the second element now receives that value. The swap is complete.

6. Example trace

Suppose the array is [10, 20, 30, 40, 50], and the user wants to swap index 1 and index 3:

  • Before swapping: arr[1] = 20 and arr[3] = 40.
  • The function receives a = &arr[1] and b = &arr[3].
  • temp = *a, so temp = 20.
  • *a = *b, so arr[1] = 40.
  • *b = temp, so arr[3] = 20.
  • After swapping: [10, 40, 30, 20, 50].

7. Why indexes are validated

The program checks whether the entered indexes are within the valid range from 0 to n - 1. This prevents accessing memory outside the array, which can cause unpredictable behavior or a program crash. It also checks whether both indexes are the same, because swapping an element with itself has no effect.

8. Swapping without a temporary variable

It is possible to swap two integers without a temporary variable using arithmetic:

void swap_without_temp(int *a, int *b) {
    if (a == b) return;

    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}
                                

However, this method can cause integer overflow when the values are very large. The temporary-variable method is simpler, safer, and easier to understand, so it is preferred in most programs.

9. Why pointer swapping is important

Pointer swapping demonstrates one of the most important uses of pointers: allowing a function to modify data that belongs to the caller. This concept is used in sorting, linked lists, dynamic memory management, and many library functions.

10. Complexity summary

Time complexity is O(1), because swapping two elements requires a fixed number of operations regardless of the array size. Space complexity is also O(1), because only one temporary variable and two pointer parameters are used.

🎯 Remember this: To swap array elements through a function, pass their addresses using &arr[i] and &arr[j]. Inside the function, exchange the values using a temporary variable and dereferencing: temp = *a, *a = *b, and *b = temp.

Frequently Asked Questions

1. Why do we pass &arr[i] instead of arr[i]?

We pass &arr[i] because the swap function needs the address of the array element to modify it permanently. If we pass arr[i], the function receives only a copy of the value, and any change made inside the function will not affect the original array.

2. What do *a and *b mean?

*a and *b dereference the pointers, meaning they access the values stored at the addresses held by a and b. Therefore, assigning to *a or *b changes the original array elements.

3. Why is a temporary variable needed?

A temporary variable preserves the original value of the first element before it is overwritten. Without it, the original value would be lost after *a = *b;, and both elements would end up with the same value.

4. What happens if both indexes are the same?

If both indexes are the same, the element is swapped with itself, so the array does not change. The program checks for this condition and prints a message instead of performing an unnecessary swap.

5. Can this swap function be used in sorting programs?

Yes. The same swap() function can be used in bubble sort, selection sort, insertion sort variants, and quicksort. Sorting algorithms repeatedly call swap to rearrange array elements into the required order.

6. What is the time complexity of swapping two array elements?

The time complexity is O(1), because the swap involves only three assignments and does not depend on the size of the array. The space complexity is also O(1), since only one temporary variable is required.

💡 Tip: After implementing this program, try using the same swap() function to reverse an entire array. Swap the first element with the last, the second with the second-last, and continue until you reach the middle.

📖 Related Tutorials

  • 3. Find the Sum of Elements in an Array Using Pointers
  • 4. Reverse an Array Using Pointers
  • 9. Linear Search in an Array Using Pointers
  • 10. Binary Search in a Sorted Array Using Pointers
  • 16. Find the Maximum Element in an Array Using Pointers
  • 17. Find the Minimum Element in an Array Using Pointers
  • 18. Sort an Array Using Pointers
  • All 30 Pointer Assignments

Previous Topic: -->> 10. Write a program in C programming to implement binary search in a sorted array using pointers.   ||   Next Topic: -->> 16. Write a program in C language to implement a function to find the maximum element in an array using pointers.


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.