Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Array

2D Array

Patterns

Excersises


C Program to Swap Two Numbers Using Pointers


Write a C program to Swap Two Numbers Using Pointers

  • Takes two integer inputs and stores their addresses in pointer variables p1 and p2.
  • Uses dereferencing to swap the values of the two integers via a temporary variable.
  • Swapping is done by manipulating the values through pointers, not directly.
  • Displays the swapped values using dereferenced pointer variables.
Example : pgm.c
#include <stdio.h>

int main() {
    int a, b, temp;
    int *p1 = &a, *p2 = &b;

    // Input two numbers
    printf("Enter first number: ");
    scanf("%d", p1);

    printf("Enter second number: ");
    scanf("%d", p2);

    // Swapping using a temporary variable and pointers
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;

    // Output after swapping
    printf("After swapping:\n");
    printf("First number = %d\n", *p1);
    printf("Second number = %d\n", *p2);

    return 0;
}

Output :

Enter first number: 10
Enter second number: 20
After swapping:
First number = 20
Second number = 10