C

Swapping Of Two Numbers In C Using Functions

In this tutorial, we are going to see how to swap two numbers using functions in C. We will create a function called swap() that allows you to perform a set of instructions by simply calling the function in the main program body.

Before we use a function. It must be defined because, in order to call it in the body of the program, the compiler must know it, i.e. know its name, its arguments, and the instructions it contains.

void swap(int *,int *);

 
There are three ways to swap two numbers in C, by using temporary variable, without temporary variable, or by creating a function.
 

Swapping Of Two Numbers In C Using Functions
#include <stdio.h>

void swap(int *,int *);


int main ()
{
  int a, b;
 
  printf("Enter two numbers: ");
  scanf("%d%d", &a, &b);

  printf("Before Swapping : a=%d,b=%d\n",a,b);

  swap(&a,&b);

  printf("After Swapping : a=%d,b=%d\n",a,b);
  return 0;
}
 

void swap(int *a,int *b){
    int tmp;
    tmp = *a;
    *a=*b;
    *b=tmp;
}

Output:

Enter two numbers: 1 2
Before Swapping
A = 1
B = 2
After Swapping
A = 2
B = 1

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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