NBC 103 • Practical #10

Swapping Two Numbers using Pointers (Call by Reference)

Aim: To demonstrate Call by Reference in C by swapping two integers using pointers.

Step-by-Step Algorithm & Logic

  • 11. Declare swap(int *x, int *y) receiving memory addresses.
  • 22. Inside swap: temp = *x, *x = *y, *y = temp.
  • 33. In main(): pass addresses swap(&a, &b).
  • 44. Print variables before and after function call.

Complete Tested Source Code

#include <stdio.h>

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main(void) {
    int a = 100, b = 250;
    printf("=== Call by Reference Pointer Swap ===\n");
    printf("Before: a = %d, b = %d\n", a, b);
    swap(&a, &b);
    printf("After:  a = %d, b = %d\n", a, b);
    return 0;
}

Sample Input:

a = 100, b = 250

Sample Output:

Before: a = 100, b = 250
After:  a = 250, b = 100

Practical Exam Viva Questions (Exp #10)

1 Questions
1

What is the role of the dereference operator (*) in the swap function?