Write c program to swap two numbers using functions
Answers
Answer:
#include<stdio.h>
void swap(int *,int *);
int main()
{
int n1,n2;
printf("\n\n Function : swap two numbers using function :\n");
printf("------------------------------------------------\n");
printf("Input 1st number : ");
scanf("%d",&n1);
printf("Input 2nd number : ");
scanf("%d",&n2);
printf("Before swapping: n1 = %d, n2 = %d ",n1,n2);
//pass the address of both variables to the function.
swap(&n1,&n2);
printf("\nAfter swapping: n1 = %d, n2 = %d \n\n",n1,n2);
return 0;
}
void swap(int *p,int *q)
{
//p=&n1 so p store the address of n1, so *p store the value of n1
//q=&n2 so q store the address of n2, so *q store the value of n2
int tmp;
tmp = *p; // tmp store the value of n1
*p=*q; // *p store the value of *q that is value of n2
*q=tmp; // *q store the value of tmp that is the value of n1
}
C Program and the output for the above question is stated below:
Output :
If the user input as 9 and 10, then the output is 10 and 9.
If the user input as 7 and 6, then the output is 6 and 7.
Explanation:
#include <stdio.h>//Header file.
void Swap(int first_number,int Second_number)//Swapping function which is used to swap the number.
{
first_number=first_number+Second_number-(Second_number=first_number);//Swaping operation.
printf("The first number is %d and the second number is %d after swapping",first_number,Second_number);//Print the number after swaping.
}
int main()//Main function.
{
int first_number,Second_number;//Variable declaration.
printf("Enter the two number for swapping: ");//Print the message for the input.
scanf("%d %d",&first_number,&Second_number);//Take the input.
Swap(first_number,Second_number);//Pass the input value to the function.
return 0;
}
Code Explanation :
- The above code is in C-language, in which the first line is used to instruct the user, then the second line is used to take the input and the third line is used to pass the value to the user-defined function for Swapping.
- Then the swap function swap the number with the help of some operation, then the swapping value is printed on the screen.
Learn More ;
- C-Program : https://brainly.in/question/3999878