Skip to main content

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

  1. Start
  2. Declare two integer variables.
  3. Declare a function that will swap two values.
  4. Initialize the integer variables.
  5. Print the original values.
  6. Call the swap function to swap the values.
  7. Print the swapped values.
  8. 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.