Swap Two Numbers using Pointers

0 June 15, 2021

In this example, We will learn a program to swap two numbers using pointers. Before that, You must have knowledge of the following topics.

Download Application: Learn C Programming with Live Compiler

Algorithm

This is the algorithm of this program

Step 1: Start
Step 2: Declare integer variables a, b and temp
Step 3: Declare pointer variables ptra and ptrb
Step 4: Take input from user and store in a and b
Step 5: Assign address of a to ptra
Step 6: Assign address of b to ptrb
Step 7: temp = *ptra
Step 8: *ptra = *ptrb
Step 9: *ptrb = temp
Step 10: Print a and b
Step 11: End

Flowchart

This is the flowchart of this program

Flowchart : Swap Two Numbers using Pointers

CODE: Swap Two Numbers using Pointers

Now, We will see the code to swap two numbers.

#include <stdio.h>

int main()
{

    int a, b;
    int *ptra, *ptrb;
    int temp;

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

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

    printf("\nThe values before swapping are: a = %d     b = %d", a, b);

    ptra = &a;
    ptrb = &b;

    temp = *ptra;
    *ptra = *ptrb;
    *ptrb = temp;

    printf("\nThe values after swapping are: a = %d    b = %d", a, b);

    return 0;

}

The output of above program is

Enter value for a: 10
Enter value for b: 20

The values before swapping are: a = 10     b = 20
The values after swapping are: a = 20    b = 10 

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Join Our Newsletter Now

Get the latest tutorials, examples and projects updates.

!

Ads

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Disable Ad Block

Want Same System