- 2071 Shrawan · 6 marks
Swap two values using pointers
Short answer
To swap two variables via a function, pass their addresses (call by reference). The function receives two pointers, dereferences them to exchange values using a temporary variable. Main calls swap(&x, &y); prints before (e.g., 15, 40) and after (40, 15).
Write a program using pointer to swap the value of two variables where the swapping operation is performed in separate function.
To change the original variables inside a function, their addresses are passed (call by reference). The function receives two pointers and exchanges the values stored at those addresses using a temporary variable.
#include <stdio.h>
void swap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
int main(void)
{
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap : x = %d, y = %d\n", x, y);
return 0;
}
Sample run
Input: 15 40
Enter two numbers: Before swap: x = 15, y = 40
After swap : x = 40, y = 15
If the values were passed instead of the addresses, only copies would be swapped and x and y would stay unchanged in main().
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Pointers in pass by reference; 2D array · Computer Programming, chapter 9
- Accessing array elements using pointer · Computer Programming, chapter 9
- Copy string converting lower to upper using pointer · Computer Programming, chapter 9 · asked 3×
- Sum and average between M and N using pointer · Computer Programming, chapter 9
- Why datatype in pointer declaration · Computer Programming, chapter 9
- Function definition; sum of two numbers · Computer Programming, chapter 6
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9
- Extreme values with two constraints · Mathematics, chapter 1 · asked 2×
- Per unit values: 100 MVA generator, two motors · Power System Analysis I, chapter 3
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3