Swap 2 Numbers in C

1. Swap 2 Numbers in C without using extra space or variable 

#include<stdio.h>


int main()
{
int a, b;
printf("Enter value of a and b");
scanf("%d %d", &a, &b);


printf("a and b before swap is = %d and %d\n", a , b);
a = a+b;
b = a-b;
a = a-b;
printf("a and b after swap is = %d and %d\n", a , b);



return 0;

}

2. Swap 2 Numbers in C using extra variable

#include<stdio.h>

int main()
{

int a, b;
printf("Enter value of a and b");

scanf("%d %d", &a, &b);

printf("a and b before swap is = %d and %d\n", a , b);
int c; // temporary variable
c = a;
a = b;
b = c;
printf("a and b after swap is = %d and %d\n", a , b);

return 0;

}




Comments

Popular posts from this blog

Setting up a USB thermal printer with a Raspberry Pi 3B+

Autostart an app on reboot - Raspberry Pi

Basic Input/Output C Program