Please answer ASAP
C program for swapping of 2 numbers .
Answers
Answered by
2
Hi friend,
This is the answer to your question:-
METHOD-1:-Using temporary variable.
#include <stdio.h>
int main()
{
int x, y, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n",x,y);
temp = x; x = y; y = temp;
printf("After Swapping\nx = %d\ny = %d\n",x,y);
return 0;
}
METHOD-2:-Using Call by reference.
#include <stdio.h>
void swap(int*, int*);
int main() { int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}
METHOD-3:-Without using third variable
#include <stdio.h>
int main()
{
int a, b;
printf("Enter two integers to swap\n");
scanf("%d%d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("a = %d\nb = %d\n",a,b);
return 0;
}
Hope it helps!
This is the answer to your question:-
METHOD-1:-Using temporary variable.
#include <stdio.h>
int main()
{
int x, y, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n",x,y);
temp = x; x = y; y = temp;
printf("After Swapping\nx = %d\ny = %d\n",x,y);
return 0;
}
METHOD-2:-Using Call by reference.
#include <stdio.h>
void swap(int*, int*);
int main() { int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}
METHOD-3:-Without using third variable
#include <stdio.h>
int main()
{
int a, b;
printf("Enter two integers to swap\n");
scanf("%d%d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("a = %d\nb = %d\n",a,b);
return 0;
}
Hope it helps!
Answered by
2
Answer -
- #include<studio.h>
- #include<conio.h>
- void main()
- {
- int a,b;
- clrscr();
- printf("enter any two numbers");
- scanf("%d%d",&a,&b);
- a=a+b;
- b=a-b;
- a=a-b;
- printf("a=%d",a);
- printf("\nb=%d",b);
- getch();
- }
Hope it will help you ❤️
Similar questions