Structure and Union
In this example, We will learn a program to swap two numbers using pointers. Before that, You must have knowledge of the following topics.
Learn C programming directly from mobile. This app includes tutorials with topics, examples and live compiler.
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
This is the flowchart of this program
Now, We will see the code to swap two numbers.
int a, b;
int *ptra, *ptrb;
printf("Enter value for a: ");
printf("\nEnter value for 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);
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
Get the latest tutorials, examples and projects updates.
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