C Program to swap two numbers explained code example
Example 1: c program to swap two arrays
#include<stdio.h>
int main()
{
int Size, i, a[10], b[10], Temp[10];
printf("\nPlease Enter the Size of the Array\n");
scanf("%d", &Size);
printf("\nPlease Enter the First Array Elements\n");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
printf("\nPlease Enter the Second Array Elements\n");
for(i = 0; i < Size; i ++)
{
scanf("%d", &b[i]);
}
for(i = 0; i < Size; i++)
{
a[i] = a[i] + b[i];
b[i] = a[i] - b[i];
a[i] = a[i] - b[i];
}
printf("\n a[%d] Array Elements After Swapping \n", Size);
for(i = 0; i < Size; i ++)
{
printf(" %d \t ",a[i]);
}
printf("\n\n b[%d] Array Elements After Swapping \n", Size);
for(i = 0; i < Size; i ++)
{
printf(" %d \t ",b[i]);
}
return 0;
}
Example 2: c program to swap two numbers 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;
}