C Program for Swap Two Numbers using Functions

Ex: Write a C program for swap two numbers using function. How to write a C program for swap two numbers using function. C program for swap two numbers using function.

Input from user:


Enter two numbers: 10 20


Expected output:


Numbers before swap:

number1=10
number2=20

Numbers after swaping:

number1=20
number2=10




  Step by step logic of the given program:



1. First declare function give it meaningful name swap().

2. Inside the main() accept input (two numbers) from user declare two varibles say no1 & no2 .

3. After that pass two values to the function using- swap(no1,no2) (calling the function).


4. In the body of swap()  declare third variable temp and swap the values using-
temp=a;
a=b;
b=temp;

5. After that print swaped values to the output screen.




  C program for swap two numbers using functions:


#include<stdio.h>
int swap(int,int);

int main()
{
int no1,no2;

printf("Enter two numbers:\n");
scanf("%d%d",&no1,&no2);

printf("Numbers before swap:\nnumber1= %d\nnumber2= %d",no1,no2);

swap(no1,no2);

}

int swap(int a,int b)
{
int temp;

temp=a;
a=b;
b=temp;

printf("\n\nNumbers after swap:\nnumber1=%d\nnumber2=%d",a,b);

return 0;

}



Above program shows the following output:


C program for swap two numbers using functions



No comments:

Post a Comment

If you have any doubts, please discuss here...👇