Program to swap two numbers using function

2 years ago Admin 0

Swap two numbers using function

This article illustrates the concept how to swap two numbers using function in c/c++.

swap two numbers using function

Here is the source code and output of both the programs.

C Programming language

Program


#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{
int x,y,res;
clrscr();
printf("Enter first number:- ");
scanf("%d",&x);
printf("Enter second number:- ");
scanf("%d",&y);
printf("\n..........Before swaping...........");
printf("\nFirst number:- %d",x);
printf("\nSecond nunber:- %d\n",y);
swap(&x,&y);
printf("\n..........After swaping.............");
printf("\nFirst number:-  %d",x);
printf("\nSecond number:- %d",y);
getch();
}
void swap(int *a,int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}

After successfully compiling and executing the above C program,output is:-

swap two numbers using function


C++ Programming language

Program


#include<iostream.h>
#include<conio.h>
void swap(int *a,int *b);
void main()
{
clrscr();
int x,y;
cout<<"Enter first number:- ";
cin>>x;
cout<<"Enter second number:- ";
cin>>y;

cout<<"\n..........Before swaping..........."<<endl;
cout<<"First number:- "<<x<<endl;
cout<<"Second nunber:- "<<y;
swap(&x,&y);

cout<<"\n..........After swaping............."<<endl;
cout<<"First number:-  "<<x<<endl;
cout<<"Second number:- "<<y;

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

After successfully compiling and executing the above C++ program,output is:-

swap two numbers using function


Comment below if you are facing any problem or you find any error in the above program and also subscribe to our newsletter for more updates.


Read more c/c++ Programs published by snapcout:-

Program to add two numbers using function
Program to add two numbers using recursion
Program to find factorial of a number using recursion
Program to find power of a number using recursion
Program to count number of digit in an integer using recursion


About article

Written By:- Admin

Published on:- 30/12/2017

Published By:- Snapcout


Don't forget to share the article if you like it:-