C program to swap two numbers
C program to swap two numbers with and without using third variable, using pointers, functions (Call by reference) and using bit-wise XOR operator. Swapping means interchanging. If the program has two variables a and b where a = 4 and b = 5, after swapping them, a = 5, b = 4. In the first C program, we use a temporary variable to swap two numbers.
Swapping of two numbers in C
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,t;
{
int x,y,t;
printf("Enter two integers\n");
scanf("%d%d",&x,&y);
scanf("%d%d",&x,&y);
printf("Before Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);
t = x;
x = y;
y = t;
x = y;
y = t;
printf("After Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);
getch();
}
}
Swapping of two numbers without third variable
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("Input two integers (a & b) to swap\n");
scanf("%d%d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
int a,b;
printf("Input two integers (a & b) 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);
getch();
}
getch();
}
Swap function in C language
#include <stdio.h>
#include<conio.h>
void swap(int*, int*); //Swap function declaration
void main()
{
int x,y;
{
int x,y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
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);
getch();
}
//Swap function definition
void swap(int *a,int *b)
{
int t;
}
//Swap function definition
void swap(int *a,int *b)
{
int t;
t = *b;
*b = *a;
*a = t;
}
*b = *a;
*a = t;
}
Swap two numbers using pointers
#include <stdio.h>
#include<conio.h>
void main()
{
int x,y,*a,*b,temp;
{
int x,y,*a,*b,temp;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
printf("After Swapping\nx = %d\ny = %d\n", x, y);
getch();
}
getch();
}
C programming code to swap using bit-wise XOR
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
{
int x,y;
scanf("%d%d",&x,&y);
printf("x = %d\ny = %d\n", x, y);
x = x ^ y;
y = x ^ y;
x = x ^ y;
y = x ^ y;
x = x ^ y;
printf("x = %d\ny = %d\n", x, y);
getch();
}
No comments:
Post a Comment