Swap 2 numbers using functions and pointers – C Program
Swap means exchanging of values of variables. We can use temporary third variable to swap or else without third variable also we can do it.
Swapping of 2 numbers can be done by passing parameters to a function.
Parameters can be passed to a function in two ways:- Pass by value.
- Pass by pointer.
Pointers are derived data types in C.
Pointers are the variables which store memory addresses as their values.
Example:
int a;int *p; // Pointer to integer
p = &a; // p stores address of variable a
Let’s write a C program to swap 2 numbers using the concept of pointers. Here we are using the function which takes 2 pointer arguments and swaps them using third variable.
Description:
x and y – integer variables.temp – it is a temporary third variable used to swap numbers.
swap() – function which swaps x and y.
Algorithm to Swap 2 integer numbers using functions:
STEP 1: STARTSTEP 2: READ two numbers
READ x, y
STEP 3: PRINT the values of x and y before swapping
PRINT x, y
STEP 4: CALL swap() function and pass the arguments
temp <- x
x <- y
y <- temp
STEP 5: PRINT the values of x and y after swapping
PRINT x, y
STEP 6: END
C Program: Swap 2 integer numbers using pointers and functions (Pass by pointers)
#include<stdio.h>#include<conio.h>
void swap(int *x, int *y);
void main()
{
int x, y;
printf("Enter 2 numbers to swap: ");
scanf("%d %d", &x, &y);
printf("Before swapping: x = %d and y = %d", x, y);
swap(&x, &y);
printf("\nAfter swapping: x = %d and y = %d", x, y);
getch();
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output:
Enter 2 numbers to swap: 4 9Before swapping: x = 4 and y = 9
After swapping: x = 9 and y = 4
C Program: Swap 2 integer numbers using functions (Pass by value)
#include<stdio.h>#include<conio.h>
void swap(int x, int y);
void main()
{
int x, y;
printf("Enter 2 numbers to swap: ");
scanf("%d %d", &x, &y);
printf("Before swapping: x = %d and y = %d", x, y);
swap(x, y);
getch();
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
printf("\nAfter swapping: x = %d and y = %d", x, y);
}
Output:
Enter 2 numbers to swap: 33 12Before swapping: x = 33 and y = 12
After swapping: x = 12 and y = 33
QUIZ:
1] Pointers in C are.- Fundamental data type.
- Derived data type.
- User defined data type.
- None.
- Value of variable.
- Address of variable.
- data type of variable.
- None.