C Program to Read Two Integers M and N & Swap their Values using functions and pointers

0
C Program

Swapping refers to the interchange of the values of two. In this C program, we will use the following features –

  1. Functions
  2. Float
  3. Pointers

We will take two floating variables from the user and pass them to a function swap() as a reference. We will use a temp variable inside the function and then swap the value.

Here is the example of C program –

  1. m = 5, n = 10
  2. Passing to swap function as reference  – &m , &n.
  3. Inside the function, temp = *ptr1  // which is  5
  4. *ptr1 = *ptr2 // here we are giving *ptr2 value into *ptr1, so now its 10
  5. *ptr2 = temp  //here *ptr2 = 5
  6. so the returned value is m = 10 and n = 5.
#include <stdio.h>
 
void swap(float *ptr1, float  *ptr2);
 
void main()
 
{
 
    float m, n; 
     
    printf("Enter the values of M and N \n");
 
    scanf("%f %f", &m, &n);
 
    printf("Before Swapping:M = %5.2ftN = %5.2f\n", m, n);
 
    swap(&m, &n);
 
    printf("After Swapping:M  = %5.2ftN = %5.2f\n", m, n);
 
}
 
/*  Function swap - to interchanges the contents of two items */
 
void swap(float *ptr1, float *ptr2)
 
{
 
    float temp;
 
    temp = *ptr1;
 
    *ptr1 = *ptr2;
 
    *ptr2 = temp;
 
}

Leave a Reply

Your email address will not be published. Required fields are marked *