Practical-18
Write a program to swap the two values using pointers and UDF.
Introduction
In this program, we will learn to swap the two values using pointers and UDF.
Algorithm
- Start
- Declare two integer variables.
- Declare a function that will swap two values.
- Initialize the integer variables.
- Print the original values.
- Call the swap function to swap the values.
- Print the swapped values.
- End
Code
Practical-18.c
// This program will demonstrate how to swap two values using pointers and UDF
#include <stdio.h>
// Declare a function that will swap two values
void swap(int* a, int* b){
int c = *a;
*a = *b;
*b = c;
}
void main(){
int x = 5;
int y = 10;
// Print the original values
printf("Original Values: x = %d and y = %d \n", x, y);
//Call the swap function to swap the values
swap(&x, &y);
//Print the swapped values
printf("Swapped Values: x = %d and y = %d \n", x, y);
}
Output
Original Values: x = 5 and y = 10
Swapped Values: x = 10 and y = 5
Explanation
In this program, we have declared a function that will swap two values. We have passed the address of the variables to the function. In the function, we have used the pointer variables to swap the values. We have called the function and passed the address of the variables to the function. We have printed the swapped values.