Swapping Numbers with Pointers

CCBeginner
Practice Now

Introduction

In C programming, pointers are powerful features that allow us to manipulate data by accessing and modifying memory locations directly. One common application of pointers is swapping values between two variables without using a third variable.

In this lab, we will learn how to create a C program that swaps two numbers using pointers. This technique is fundamental in various programming scenarios and demonstrates the practical use of pointers for memory manipulation.

The lab will guide you through creating a program from scratch, compiling it, and running it to see the swap in action.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/PointersandMemoryGroup(["Pointers and Memory"]) c(("C")) -.-> c/FileHandlingGroup(["File Handling"]) c/BasicsGroup -.-> c/variables("Variables") c/PointersandMemoryGroup -.-> c/pointers("Pointers") c/FileHandlingGroup -.-> c/create_files("Create Files") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/variables -.-> lab-123350{{"Swapping Numbers with Pointers"}} c/pointers -.-> lab-123350{{"Swapping Numbers with Pointers"}} c/create_files -.-> lab-123350{{"Swapping Numbers with Pointers"}} c/user_input -.-> lab-123350{{"Swapping Numbers with Pointers"}} c/output -.-> lab-123350{{"Swapping Numbers with Pointers"}} end

Understanding Pointers in C

Before we start coding, let's understand what pointers are and how they work in C.

What is a Pointer?

A pointer is a variable that stores the memory address of another variable. Pointers are essential in C because they allow direct access to memory and enable more efficient manipulation of data.

Pointer Syntax

In C, pointers are declared using the asterisk (*) symbol:

int *ptr;    // Declares a pointer to an integer

When working with pointers, we use two important operators:

  • The address-of operator (&) - gets the memory address of a variable
  • The dereference operator (*) - accesses the value stored at the address held by a pointer

Creating Our First File

Let's start by creating our main C file in the project directory. Open the IDE and create a new file named main.c:

  1. In the file explorer panel (left side), navigate to /home/labex/project
  2. Right-click and select "New File"
  3. Name the file main.c
  4. Add the following basic structure to the file:
#include <stdio.h>

int main() {
    // We will add our code here

    return 0;
}

This creates a simple C program with the standard input/output library included and a main function that returns 0 when the program completes successfully.

Creating the Swap Program Structure

Now that we understand pointers, let's build our swap program step by step.

Declaring Variables and Pointers

We need to declare:

  1. Two integer variables (a and b) to hold the values we want to swap
  2. Two integer pointers (ptra and ptrb) to store the addresses of a and b
  3. A temporary variable (temp) to help with the swap operation

Update your main.c file with the following code:

#include <stdio.h>

int main() {
    // Declare variables
    int a, b;
    int *ptra, *ptrb;
    int temp;

    // Get input from user
    printf("Enter value for a: ");
    scanf("%d", &a);

    printf("Enter value for b: ");
    scanf("%d", &b);

    // Display original values
    printf("\nOriginal values:\n");
    printf("a = %d\n", a);
    printf("b = %d\n", b);

    // We will add more code here in the next step

    return 0;
}

Understanding the Code

Let's analyze what we've done so far:

  1. We declared two integers a and b that will hold the values we want to swap
  2. We declared two integer pointers ptra and ptrb that will store the memory addresses of a and b
  3. We declared a temporary integer temp that will help us with the swap operation
  4. We added code to prompt the user to enter values for a and b
  5. We added code to display the original values of a and b

Notice that in the scanf function, we use the address-of operator (&) to tell the function where to store the input values in memory.

Implementing the Swap Logic

Now let's implement the actual swap logic using pointers.

Assigning Addresses to Pointers

First, we need to make our pointers point to our variables by assigning the addresses of a and b to ptra and ptrb respectively:

// Assign addresses to pointers
ptra = &a;
ptrb = &b;

The Swap Algorithm Using Pointers

The key to swapping values with pointers is to manipulate the values at the memory locations, not just the pointers themselves. Here's how we'll do it:

  1. Store the value of a (accessed via *ptra) in the temporary variable temp
  2. Assign the value of b (accessed via *ptrb) to a (by using *ptra)
  3. Assign the temporary value (original value of a) to b (by using *ptrb)

Update your main.c file by adding the following code where indicated in the previous step:

#include <stdio.h>

int main() {
    // Declare variables
    int a, b;
    int *ptra, *ptrb;
    int temp;

    // Get input from user
    printf("Enter value for a: ");
    scanf("%d", &a);

    printf("Enter value for b: ");
    scanf("%d", &b);

    // Display original values
    printf("\nOriginal values:\n");
    printf("a = %d\n", a);
    printf("b = %d\n", b);

    // Assign addresses to pointers
    ptra = &a;
    ptrb = &b;

    // Display memory addresses (optional but helpful for understanding)
    printf("\nMemory addresses:\n");
    printf("Address of a: %p\n", ptra);
    printf("Address of b: %p\n", ptrb);

    // Swap the values using pointers
    temp = *ptra;    // Store value of a in temp
    *ptra = *ptrb;   // Assign value of b to a
    *ptrb = temp;    // Assign original value of a to b

    // Display swapped values
    printf("\nAfter swapping:\n");
    printf("a = %d\n", a);
    printf("b = %d\n", b);

    return 0;
}

Understanding the Swap Logic

Let's understand exactly how the swap works:

  1. temp = *ptra; - The * operator dereferences the pointer, accessing the value at the memory location. This line stores the value of a in temp.
  2. *ptra = *ptrb; - This assigns the value of b to the memory location of a, effectively changing a's value.
  3. *ptrb = temp; - This assigns the original value of a (stored in temp) to the memory location of b, completing the swap.

After these operations, the variables a and b have exchanged values without directly modifying them - we only modified the values at their memory locations.

Compiling and Testing the Swap Program

Now that we have completed our program, let's compile and run it to see the results.

Compiling the Program

To compile the program, we'll use the GNU C Compiler (gcc). Open a terminal in the WebIDE and run the following command:

cd ~/project
gcc main.c -o swap_program

This command compiles our main.c file and creates an executable named swap_program.

Running the Program

Now let's run our program to see if it correctly swaps the values:

./swap_program

You'll be prompted to enter values for a and b. For example, let's enter:

  • a = 5
  • b = 10

The program should display:

  • The original values: a = 5, b = 10
  • The memory addresses of a and b
  • The swapped values: a = 10, b = 5

Understanding the Output

When you run the program, you'll see several sections of output:

  1. Original values - Shows the values before swapping
  2. Memory addresses - Shows where the variables are stored in memory (will be different each time you run the program)
  3. After swapping - Shows the values after the swap operation

Try running the program multiple times with different input values to confirm that the swap works consistently.

How Does It Work Behind the Scenes?

Let's visualize what happens in memory:

  1. Initially, if a = 5 and b = 10, they each have their own memory locations
  2. ptra points to the memory location of a
  3. ptrb points to the memory location of b
  4. During the swap:
    • temp gets the value at ptra (which is 5)
    • The value at ptra is changed to the value at ptrb (which is 10)
    • The value at ptrb is changed to temp (which is 5)
  5. After the swap, a = 10 and b = 5, effectively swapping their values

This demonstrates the power of pointers - they allow us to indirectly modify values by manipulating memory locations directly.

Summary

In this lab, we learned how to use pointers in C to swap the values of two variables. Key concepts covered include:

  1. Pointers: Variables that store memory addresses of other variables
  2. Memory Addresses: Unique locations in computer memory where data is stored
  3. Pointer Operations:
    • The address-of operator (&) to get a variable's memory address
    • The dereference operator (*) to access the value at a memory address
  4. Swap Algorithm: Using a temporary variable and pointers to exchange values

This technique is a fundamental concept in C programming and demonstrates the power of pointers for memory manipulation. It can be applied in various programming scenarios such as sorting algorithms, data structure operations, and function implementations.

By understanding how to manipulate data through memory addresses, you've taken an important step in mastering C programming and computer memory concepts.