Here, we have a basic program example to swap two numbers using functions using different languages. This program is created in c language, c++, Java, and Python.
Function to swap numbers in C language
#include<stdio.h>
void swap(int *,int *);
int main()
{
int num1,num2;
printf("Input 1st number : ");
scanf("%d",&num1);
printf("Input 2nd number : ");
scanf("%d",&num2);
printf("Before swapping: Number1 = %d, Number2 = %d ",num1,num2);
swap(&num1,&num2);
printf("\nAfter swapping: Number1 = %d, Number2 = %d \n\n",num1,num2);
return 0;
}
void swap(int *p,int *q)
{
int tmp;
tmp = *p;
*p=*q;
*q=tmp;
}
Function to swap numbers in C++ language
#include<iostream>
using namespace std;
void swap(int ,int );
int main()
{
int num1,num2;
cout<<"Enter the first number : ";
cin>>num1;
cout<<"Enter the second number : ";
cin>>num2;
cout<<"\nAfter Swapping of Two Numbers:"<<endl;
swap(num1,num2);
return 0;
}
void swap(int x,int y)
{
int z;
z=x;
x=y;
y=z;
cout<<"First Number is: "<<x<<endl;
cout<<"Second Number is: "<<y<<endl;
}
Function to swap numbers in Python language
def swap(x,y):
print("Before swapping First Number is: ",x)
print("Before swapping Second Number is: ",y)
x,y=y,x
return x,y
a=int(input("Enter First Number: "))
b=int(input("Enter Second Number: "))
a,b=swap(a,b)
print("After swapping First Number is: ",a)
print("After swapping Second Number is: ",b)
Function to swap numbers in Java language
import java.util.*;
class SwapFunc
{
int a,b;
public void swap(SwapFunc swp)
{
int temp;
temp=swp.a;
swp.a=swp.b;
swp.b=temp;
}
public static void main(String s[])
{
SwapFunc objSwp= new SwapFunc();
Scanner sc=new Scanner(System.in);
System.out.print("Enter first number: ");
objSwp.a=sc.nextInt();
System.out.print("Enter second number: ");
objSwp.b=sc.nextInt();
objSwp.swap(objSwp);
System.out.println("After swapping First Number: " + objSwp.a + "\n ");
System.out.println("After swapping Second Number: " + objSwp.b + "\n ");
}
}