C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Swap numbers using pointers

C Program: Swap numbers using pointers

C

#include <stdio.h>

 

int main() {

    int a, b, temp;

    int *ptr1, *ptr2;

 

    // Input two numbers

    printf("Enter first number: ");

    scanf("%d", &a);

    printf("Enter second number: ");

    scanf("%d", &b);

 

    // Assign addresses to pointers

    ptr1 = &a;

    ptr2 = &b;

 

    // Swap using pointers

    temp = *ptr1;

    *ptr1 = *ptr2;

    *ptr2 = temp;

 

    // Display results

    printf("\nAfter swapping:\n");

    printf("First number = %d\n", a);

    printf("Second number = %d\n", b);

 

    return 0;

}

Output

 
OUTPUT :
Enter first number: 10
Enter second number: 20

After swapping:
First number = 20
Second number = 10

Explanation

  • The program uses pointers ptr1 and ptr2 to access and modify the values of variables a and b.
  • The swapping process happens directly in memory through the pointers.
  • temp temporarily stores one value during the exchange.