Tuesday, June 30, 2020

Knapsack Using Bitmask

#include<bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false),cin.tie(NULL)
#define ll long long
#define endl "\n"

using namespace std;


/*fast io
ios_base::sync_with_stdio(false);
cin.tie(NULL);
*/

ll val[22] , wgh[22];


int main()
{
    fastio;
    int n ;
    cin>>n;
    for(int i = 0 ; i<n ; i++){
        cin>>val[i]>>wgh[i];
    }
    ll cap;
    cin>>cap;

    int tot = 1<<n;
    ll ans = 0;
    for(int mask = 0  ; mask < tot ; mask++){
        ll sum = 0 , value = 0;
        for(int i = 0 ; i<n ; i++){
            if((mask&(1<<i)) != 0){ /// mask = 01010 , 1<<3 = 1000
                sum += wgh[i];
                value += val[i];
            }
        }
        if(sum <= cap) ans = max(ans , value);
    }

    cout<<ans<<endl;


    return 0;
}

Memory Optimizing Using Bitmusk

#include<bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false),cin.tie(NULL)
#define ll long long
#define endl "\n"
#define MAX ((int)(1e9 + 7))

using namespace std;


/*fast io
ios_base::sync_with_stdio(false);
cin.tie(NULL);
*/

int arr[MAX>>5];

int main()
{
//    fastio;
    int q;
    cin>>q;
    while(q--){
        int num;
        cin>>num;
        int idx = num>>5 , pos = num&31; /// idx = num/32 , pos = num%32
        if( arr[idx]&(1<<pos) ){
            cout<<"1\n";
        }
        else{
            cout<<"0\n";
            arr[idx] = arr[idx]|(1<<pos);
            /// 1<<2 = 100
            /// arr[idx] = arr[idx] | (100)
        }
    }
    return 0;
}

GCD and LCM Formula

GCD Function:
ll gcd(ll a , ll b)
{
    if(b<a) swap(a,b);
//    if(a == 0) return b;

    while(a > 0){
        ll mod = b%a;   /// mod<a
        b = a;
        a = mod;
    }

    return b;
}

LCM Function:
long long lcm(ll a , ll b)
{
    long long ans = 1LL*a*b;
    ans = ans/gcd(a,b);
    return ans;
}

LCM and GCD Program

#include<bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false),cin.tie(NULL)
#define ll long long
#define endl "\n"

using namespace std;


/*fast io
ios_base::sync_with_stdio(false);
cin.tie(NULL);
*/

/// gcd ( 0 , a ) = a

ll gcd(ll a , ll b)
{
    if(b<a) swap(a,b);
//    if(a == 0) return b;

    while(a > 0){
        ll mod = b%a;   /// mod<a
        b = a;
        a = mod;
    }

    return b;
}

long long lcm(ll a , ll b)
{
    long long ans = 1LL*a*b;
    ans = ans/gcd(a,b);
    return ans;
}

int main()
{
    int a, b;


    int n;
    cin>>n;

    ll ans = 0 ;
    ll val = 1; /// val ( 1 , a ) = a

    for(int i = 1 ; i<=n ; i++){
        ll a;
        cin>>a;
        val = a*val/__gcd(a,val);
        ans = __gcd(ans , a);
    }

    while(1){
        cin>>a>>b;
        cout<<gcd(a,b)<<" "<<__gcd(a,b)<<endl;
        cout<<lcm(a,b)<<endl;
    }
    return 0;
}

Bit on, off and check Program

#include <bits/stdc++.h>

using namespace std;

int main(){
    int n, pos;

    while(scanf("%d %d", &n, &pos)){
        int bit_on = n|(1<<pos);
        int bit_off = n&(~(1<<pos));
        int bit_check = n&(1<<pos);

        printf("Bit On: %d\nBit off: %d\nBit Check: %d\n", bit_on, bit_off, bit_check);
    }


    return 0;
}

Monday, June 29, 2020

Contest 1 Problem

Contest 1:
1. 1097B - Petr and a Combination Lock
2. 550B - Preparing Olympiad
3. Chef and Queries Problem Code: CHEFQUE
4. 1202A - You Are Given Two Binary Strings...
5. 579A - Raising Bacteria
6. 467B - Fedor and New Game
7. 1095C - Powers Of Two
8. 1151B - Dima and a Bad XOR
9. 158A - Next Round
10. 486A - Calculating Function


Class Materials

Amar Ischool

Contest 1:
link: https://vjudge.net/contest/379591
password: adhocandbit

Contest 2:
link : https://vjudge.net/contest/380446
password : contest2

GitHub repository link for every class code: https://github.com/pioneerAlpha/CP_Beginner_B1

class 1 video link: https://youtu.be/N9l4fSelqn4
Class 2 video link: https://youtu.be/kQmaXaJGdRg
Class 3(part 1): https://youtu.be/TDT2cZehoCo
Class 3(part 2): https://youtu.be/ZJBbephDMUc
Class 4, Discussion Class 1: https://youtu.be/Tp8O2MW_XPs
Class 4 video: https://youtu.be/7HIgCK0IDRw

Bit Position Formula

Left Shift:
Formula: n*2^x = n*pow(2,x);
where n is number and x is bit positon.

Right Shift:
Formula: n/2^x = n/pow(2,x);
Where n is number and x is bit positon.

Xth Position Bit On:
Formula: n|(1<<x)
where x is positon of bit.

Xth Position Bit Off:
Formula: n&(~(1<<x))
where x is positon of bit.

Xth Positon Bit Check:
Formula: n&(1<<x)
where x is positon of bit.

if(n&(1<<x) == 0) that means bit off
otherwise on

Thursday, June 25, 2020

STL

Vector:
--Declaration
--> vector <data type> name;
--Insert Element
--> to push an element : name.push_back(element);
--To check Size
--> to check size : name.size();
--Erase Element
--> to erase an element : name.erase(name.begin() + index of the element);
--> to erase several elements : name.erase(name.begin() + index of the 1st element , name.begin() + index of the last element + 1 );
--Clear All Element
--> to erase all elements : name.clear();
--Check data Empty  or not
--> true if the container size is 0, false otherwise: name.empty();

Stack:
--Declaration
--> stack < data type > name
--Insert Element
--> to push an element : name.push(data);
--Access top Element:
--> to access the top element : name.top();
--Remove top Element:
--> to remove the top element : name.pop();
--To check Size
--> to check size : name.size();
--Check data Empty  or not
--> true if the underlying container's size is 0, false otherwise: name.empty();
--Swap between Elemen
-->xchanges the contents of the container adaptor: foo.swap(bar)

Queue:
--Declaration
--> queue < data type > name
--Insert Element
--> to push an element : name.push(data);
--Access top Element:
--> to access the top element : name.front();
--Remove top Element:
--> to remove the top element : name.pop();
--To check Size
--> to check size : name.size();
--Check data Empty  or not
--> true if the underlying container's size is 0, false otherwise: name.empty();
--Swap between Element
-->xchanges the contents of the container adaptor: foo.swap(bar)

Deque:
--Declaration
--> declare : deque < data type > name;
--Insert Element
--> to insert an element from left end : name.push_front(value);
--> to insert an element from right end : name.push_back(value);
--Access Element
--> to access :name.front() and name.back();
--Remove top Element:
--> to remove the front element : name.pop_front();
--> to remove the back element : name.pop_back();
--To check Size
--> to check size : name.size();
--Check data Empty  or not
--> true if the underlying container's size is 0, false otherwise: name.empty();

Priority_queue:
--Declaration
-- declare : priority_queue < data type > name;
--Insert Element
-- to insert an element : name.push(data);
--Access Element
-- to access the top element : name.top();
--Erase Element
-- to erase the top element : name.pop();
--Max Heap
int arr[] = {5 , 6 , 4 , 10 , 9 , -9 , -1};
-- for(int i = 0 ; i<n ; i++) pqq.push(arr[i]);
--Min Heap
int arr[] = {5 , 6 , 4 , 10 , 9 , -9 , -1};
-- for(int i = 0 ; i<n ; i++) pqq.push(-arr[i]);
while(!pqq.empty()){

        printf("%d\n",-pqq.top());
        pqq.pop();
    }

Set:
--Declaration
-- declare : set < data type > name;
--Insert Element
-- to insert an element : name.insert();
--Declare Iterator
-- to declare an iterator : set < data type > :: iterator name;
--Access Element
-- access element using iterator
for(it = st.begin() ; it != st.end() ; it++){

        printf("%d\n",*it);

    }
--Erase Element
-- to erase : name.erase(value);
--Clear Elment
-- to clear all elements : name.clear();

Left Shift and Right Shift Formula

#include <bits/stdc++.h>

using namespace std;

int main(){

    int a, x;
    while(scanf("%d %d", &a, &x)){
        int left = a*pow(2,x);
        int right = a/pow(2,x);

        printf("Left Shift is: %d and Right Shift is: %d\n", left, right);
    }

    return 0;
}

Friday, June 19, 2020

Bangla Programming Blog Links

শাফায়েতের ভাই  এর ব্লগ- http://www.shafaetsplanet.com/planetcoding/
ইকরাম মাহমুদ ফাহিমের ভাই এর ব্লগ- https://sites.google.com/site/smilitude/
প্রোগ্রামিং কনসেপ্ট- https://sites.google.com/site/programinggconcept/
মুকিত চৌধুরীর ভাই এর ব্লগ- http://mukitmkbs.wordpress.com/
জোবায়ের হাসানের ভাই এর ব্লগ- http://zobayer2009.wordpress.com/
অনিন্দ্য সুন্দর পালের ভাই এর ব্লগ- http://binaryrongo.wordpress.com/
আলাভোলার ভাই এর ব্লগ- http://ami-alavola.rhcloud.com
আহমাদ ফাইয়াজ ভাই এর  ব্লগ- http://itsfaiyaz.wordpress.com/
বিধান ভাই এর ব্লগ – http://bidhanr.wordpress.com/
এরর ভাই এর ব্লগ – https://sites.google.com/site/erorown/
সুবিন ভাইয়ের সাইট- http://cpbook.subeen.com/
ফাইয়াজ বিন হোসেন ভাই এর ব্লগ- http://faiazerblog.blogspot.com/
ফারসান ভাই এর ব্লগ- http://potasiyam.com/farsan/
আনা ফারিহা ম্যাম এর ব্লগ – http://chorui12.blogspot.com/
শরীফ ভাই এর স্বপ্নরাজ্য – http://www.techsharif.com/
শিখর ভাই এর ব্লগ – http://shikhorroy.wordpress.com/
সায়েফ ভাই এর ব্লগ – http://sketchingdream.wordpress.com/
আসিফ ভাই এর হ-য-ব-র-ল – http://www.abuasifkhan.me/
আবারো আলসেমি লাগতাসে পরে আবার লিখব :p …………………………………

Thursday, June 18, 2020

Counting Sort Program

#include<stdio.h>


int k=0; // for storing the maximum element of input array

/* Method to sort the array */
void sort_func(int A[],int B[],int n)
{
int count[k+1],t;
for(int i=0;i<=k;i++)
{
//Initialize array count
count[i] = 0;
}
for(int i=0;i<n;i++)
{
    // count the occurrence of elements u of A
    // & increment count[u] where u=A[i]
t = A[i];
count[t]++;
}
for(int i=1;i<=k;i++)
{
    // Updating elements of count array
count[i] = count[i]+count[i-1];
}
for(int i=0;i<n;i++)
{
// Add elements of array A to array B
t = A[i];
B[count[t]] = t;
    // Decrement the count value by 1
count[t]=count[t]-1;
}
}
int main()
{
int n;
printf("Enter the size of the array :");
scanf("%d", &n);

// A is the input array and will store elements entered by the user
// B is the output array having the sorted elements
int A[n],B[n];
printf("Enter the array elements: ");
for(int i=0;i<n;i++)
{
scanf("%d", &A[i]);
if(A[i]>k)
{
// k will have the maximum element of A[]
k = A[i];
}
}

sort_func(A,B,n);

// Printing the elements of array B
for(int i=1;i<=n;i++)
{
printf("%d ", B[i]);
}

printf("\n");

return 0;
}

Counting Sort Algorithm

Counting Sort Algorithm is an efficient sorting algorithm that can be used for sorting elements within a specific range. This sorting technique is based on the frequency/count of each element to be sorted and works using the following algorithm-
  • Input: Unsorted array A[] of n elements
  • Output: Sorted arrayB[]
Step 1: Consider an input array A having n elements in the range of 0 to k, where n and k are positive integer numbers. These n elements have to be sorted in ascending order using the counting sort technique. Also note that A[] can have distinct or duplicate elements
Step 2: The count/frequency of each distinct element in A is computed and stored in another array, say count, of size k+1. Let u be an element in A such that its frequency is stored at count[u].
Step 3: Update the count array so that element at each index, say i, is equal to -
count image
Step 4: The updated count array gives the index of each element of array A in the sorted sequence. Assume that the sorted sequence is stored in an output array, say B, of size n.
Step 5: Add each element from input array A to B as follows:
  1. Set i=0 and t = A[i]
  2. Add t to B[v] such that v = (count[t]-1).
  3. Decrement count[t] by 1
  4. Increment i by 1
Repeat steps (a) to (d) till i = n-1
Step 6: Display B since this is the sorted array
Pictorial Representation of Counting Sort with an Example
Let us trace the above algorithm using an example:
Consider the following input array A to be sorted. All the elements are in range 0 to 9
A[]= {1, 3, 2, 8, 5, 1, 5, 1, 2, 7}
Step 1: Initialize an auxiliary array, say count and store the frequency of every distinct element. Size of count is 10 (k+1, such that range of elements in A is 0 to k)
count arrayFigure 1: count array
Step 2: Using the formula, updated count array is -
update count arrayFigure 2: Formula for updating count array
updated arrayFigure 3 : Updated count array
Step 3: Add elements of array A to resultant array B using the following steps:
  • For, i=0, t=1, count[1]=3, v=2. After adding 1 to B[2], count[1]=2 and i=1
    For i =0Figure 4: For i=0
  • For i=1, t=3, count[3]=6, v=5. After adding 3 to B[5], count[3]=5 and i=2
    For i =1Figure 5: For i=1
  • For i=2, t=2, count[2]= 5, v=4. After adding 2 to B[4], count[2]=4 and i=3
    For i =2Figure 6: For i=2
  • For i=3, t=8, count[8]= 10, v=9. After adding 8 to B[9], count[8]=9 and i=4
    For i =3Figure 7: For i=3
  • On similar lines, we have the following:
    For i =4Figure 8: For i=4
    For i =5Figure 9: For i=5
    For i =6Figure 10: For i=6
    For i =7Figure 11: For i=7
    For i =8Figure 12: For i=8
    For i =9Figure 13: For i=9
Thus, array B has the sorted list of elements.

Program for Counting Sort Algorithm

Below we have a simple program in C++ implementing the counting sort algorithm:
#include<iostream>
using namespace std;

int k=0;  // for storing the maximum element of input array

/* Method to sort the array */
void sort_func(int A[],int B[],int n)    
{
 int count[k+1],t;
 for(int i=0;i<=k;i++)
 {
  //Initialize array count
  count[i] = 0;
 }
 for(int i=0;i<n;i++)
 {
     // count the occurrence of elements u of A 
     // & increment count[u] where u=A[i]
  t = A[i];
  count[t]++;   
 }
 for(int i=1;i<=k;i++)
 {
     // Updating elements of count array 
  count[i] = count[i]+count[i-1];            
 }
 for(int i=0;i<n;i++)
 {
  // Add elements of array A to array B
  t = A[i];
  B[count[t]] = t;          
     // Decrement the count value by 1
  count[t]=count[t]-1;  
 }
}
int main()
{
 int n;
 cout<<"Enter the size of the array :";
 cin>>n;
 
 // A is the input array and will store elements entered by the user
 // B is the output array having the sorted elements 
 int A[n],B[n]; 
 cout<<"Enter the array elements: ";
 for(int i=0;i<n;i++)        
 {
  cin>>A[i];
  if(A[i]>k)
  {
   // k will have the maximum element of A[]
   k = A[i];              
  }
 }
 
 sort_func(A,B,n);        
 
 // Printing the elements of array B
 for(int i=1;i<=n;i++)       
 {
  cout<<B[i]<<" ";
 }
 
 cout<<"\n";
 return 0;
}
The input array is the same as that used in the example:
OutputFigure 14: Output of Program
Note: The algorithm can be mapped to any programming language as per the requirement.

Time Complexity Analysis

For scanning the input array elements, the loop iterates n times, thus taking O(n) running time. The sorted array B[] also gets computed in n iterations, thus requiring O(n) running time. The count array also uses k iterations, thus has a running time of O(k). Thus the total running time for counting sort algorithm is O(n+k).
Key Points:
  • The above implementation of Counting Sort can also be extended to sort negative input numbers
  • Since counting sort is suitable for sorting numbers that belong to a well-defined, finite and small range, it can be used asa subprogram in other sorting algorithms like radix sort which can be used for sorting numbers having a large range
  • Counting Sort algorithm is efficient if the range of input data (k) is not much greater than the number of elements in the input array (n). It will not work if we have 5 elements to sort in the range of 0 to 10,000
  • It is an integer-based sorting algorithm unlike others which are usually comparison-based. A comparison-based sorting algorithm sorts numbers only by comparing pairs of numbers. Few examples of comparison based sorting algorithms are quick sort, merge sort, bubble sort, selection sort, heap sort, insertion sort, whereas algorithms like radix sort, bucket sort and comparison sort fall into the category of non-comparison based sorting algorithms.

Advantages of Counting Sort:

  • It is quite fast
  • It is a stable algorithm
Note: For a sorting algorithm to be stable, the order of elements with equal keys (values) in the sorted array should be the same as that of the input array.

Disadvantages of Counting Sort:

  • It is not suitable for sorting large data sets
  • It is not suitable for sorting string values

Even or Odd Program

C programs to check odd or even using different methods. In the decimal number system, even numbers are exactly divisible by two while odd numbers are not. We can use modulus operator '%' which returns the remainder, for example, 4%3 = 1 (remainder when four is divided by three

Odd or even program in C using modulus operator

#include <stdio.h>
int main()
{
  int n;
  printf("Enter an integer\n");
  scanf("%d", &n);
  if (n%2 == 0)
    printf("Even\n");
  else
    printf("Odd\n");
  return 0;
}
We can use bitwise AND (&) operator to check odd or even. For example, consider binary of 7 (0111), (7 & 1 = 1). You may observe that the least significant bit of every odd number is 1. Therefore (odd_number & 1) is one always and also (even_number & 1) is always zero.

C program to find odd or even using bitwise operator

#include <stdio.h>
int main()
{
  int n;
 
  printf("Input an integer\n");
  scanf("%d", &n);
  if (n & 1 == 1)
    printf("Odd\n");
  else
    printf("Even\n");
 
  return 0;
}
Another Way:
//আমি আরেকটু শর্টকাট করি নিচের মত করে

if(num & 1)
    printf("odd");
else
    printf("even);
Another Way Less Efficient Code:
if ((n & -n) == 1)
    printf("odd");
else
    printf("even");

Another Way: Using XOR 
if ( (num ^ 1) < num)
    printf("odd");
else
    printf("even");

3. Using Bitwise AND Operator (&)

Bitwise operators work on individual bits of a variable. For example, when you perform an operation on 5 and 1 (5 & 1), the result is 1. Let's see how it works:
 5       - 0101  ( 5 in binary form ) - 5 is odd number here.
 1       - 0001  ( 1 in binary form )
5 & 1    - 0001  ( result after performing bitwise & i.e 1)
If you see above, after performing bitwise on 5 and 1, we got result 1. Let's perform bitwise & on 4 (even number ) and 1.
4        - 0100 ( 4 in binary form) - 4 is even number here.
1        - 0001 ( 1 in binary form) - 1 is even number here.
4 & 1    - 0000 ( result is 0)
The rules of Bitwise & when performed on bits 0 and 1.
0 & 0 - 0
0 & 1 - 0
1 & 0 - 0
1 & 1 - 1
Now, let's go through the solution, if you see in the above examples when you perform bitwise & on an odd number and 1, we got result 1, when you perform on even number and 1, it is 0, which means:
( odd number ) & 1 is 1.
( even number ) & 1 is 0.
So the algorithm is:
if( number & 1 == 0) {
   even number
} else {
   odd number
}
The code snippet is below:
private void isEvenM3(int i) {
       
        int res = i & 1;
       
        if(res == 0) {
            System.out.println(i +" is Even Number");
        } else {
            System.out.println(i + " is Not Even Number");
        }
    }

4. Using Left Shift and Right Shift Operators (<< , >>)

Similar to Bitwise operators, Left shift and Right shift operators work on individual bits of a number. Let's see how Left shift operator and right shift operator work. For example:
5 >> 1 - (0101) >> 1 = 0010, i.e., 2
Here we performed right shift once, i.e., 5 in binary form is 0101 and doing right shift once, it becomes 0010, as right most digit goes away. Therefore 5 >> 1 is 2. Now let's see how left shift operator works:
5 << 1 - ( 0101 ) << 1 = 1010 i.e.,10
Here, when you do left shift of 1 bit, the left most bit goes away.
Let's see one more example, now take 4 for our purpose.
4 >> 1 - ( 0100 ) >> 1 = 2.
4 << 1 - ( 0100 ) << 1 = 8.
Now we understand how left shift and right shift operators works. Now let's see how to solve our problem using left and right shift operators. Now take 4, 5 for our reference.
Now I am going to perform one right shift and one left shift on both 4 and 5.
( 4 >> 1 ) << 1 = ( 2 ) << 1 = 4.
( 5 >> 1 ) << 1 = ( 2 ) << 1 = 4.
If you observe above, for even numbers, we are getting the same number again, but for odd numbers, we are getting a different number. We can make use of this algorithm to solve our problem.
if ( ( num >> 1) << 1 == num) {
    even number
} else {
    odd number
}
The code snippet is below:
private void isEvenM4(int i) {
        int res = (i >> 1) << 1; // right by 1 bit and then left shift by 1 bit
        if(res == i) {
            System.out.println(i +" is Even Number");
        } else {
            System.out.println(i + " is Not Even Number");
        }       
    }

Example 2: Check Whether Number is Even or Odd using ternary operators

#include <iostream>
using namespace std;

int main()
{
    int n;

    cout << "Enter an integer: ";
    cin >> n;
    
    (n % 2 == 0) ? cout << n << " is even." :  cout << n << " is odd.";
    
    return 0;
}

Swapping Program



C program to swap two numbers with and without using third variable, using pointersfunctions (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.

C Program to Swap two Numbers

Given two numbers, write a C program to swap the given numbers.
Input : x = 10, y = 20;
Output : x = 20, y = 10

Input : x = 200, y = 100
Output : x = 100, y = 200

Swapping of two numbers in C

#include <stdio.h>
int main()
{
  int x, y, t;
  printf("Enter two integers\n");
  scanf("%d%d", &x, &y);
  printf("Before Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);
  t = x;
  x = y;
  y = t;
  printf("After Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);
  return 0;
}
The output of the program:
Enter two integers
23
45
Before Swapping
First integer = 23
Second integer = 45
After Swapping
First integer = 45
Second integer = 23

Swapping of two numbers without third variable

You can also swap two numbers without using third variable. In this case C program will be as follows:
#include <stdio.h>
int 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;
   printf("a = %d\nb = %d\n",a,b);
   return 0;
}
Output of program:
Swap numbers C program output
To understand the logic, choose the variables 'a' and 'b' as '7' and '9' respectively, and do according to the program. You can choose any other combination of numbers as well. Sometimes it's an excellent way to understand a program.

Swap Numbers Without Using Temporary Variables

#include <stdio.h>
int main() {
    double a, b;
    printf("Enter a: ");
    scanf("%lf", &a);
    printf("Enter b: ");
    scanf("%lf", &b);

    // Swapping

    // a = (initial_a - initial_b)
    a = a - b;   
 
    // b = (initial_a - initial_b) + initial_b = initial_a
    b = a + b;

    // a = initial_a - (initial_a - initial_b) = initial_b
    a = b - a;

    printf("After swapping, a = %.2lf\n", a);
    printf("After swapping, b = %.2lf", b);
    return 0;
}
Output
Enter a: 10.25
Enter b: -12.5
After swapping, a = -12.50
After swapping, b = 10.25

Swap function in C language

In this method we will make a function to swap numbers. We will use call by reference.
#include <stdio.h>
void swap(int*, int*); //Swap function declaration
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;
}
//Swap function definition
void swap(int *a, int *b)
{
   int t;
   t  = *b;
   *= *a;
   *= t;
}

Swap two numbers using pointers

#include <stdio.h>
int main()
{
   int x, y, *a, *b, 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);
 
   a = &x;
   b = &y;
 
   temp = *b;
   *b   = *a;
   *a   = temp;
   printf("After Swapping\nx = %d\ny = %d\n", x, y);
 
   return 0;
}

C programming code to swap using bit-wise XOR

#include <stdio.h>
int main()
{
  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;
  printf("x = %d\ny = %d\n", x, y);
  return 0;
}
How to write a function to swap?
Since we want the local variables of main to modified by swap function, we must them using pointers in C.
// C program to swap two variables using a 
// user defined swap()
#include <stdio.h>
  
// This function swaps values pointed by xp and yp
void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
    swap(&x, &y);
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}
Output:
Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 
How to do in C++?
In C++, we can use references also.
// C++ program to swap two variables using a 
// user defined swap()
#include <stdio.h>
  
// This function swaps values referred by 
// x and y,
void swap(int &x, int &y)
{
    int temp = x;
    x = y;
    y = temp;
}
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
    swap(x, y);
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}
Output:
Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 
Is there a library function?
We can use C++ library swap function also.
// C++ program to swap two variables using a 
// user defined swap()
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
    swap(x, y);
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}
Output:
Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 

Sorting algorithms use swapping to arrange numbers in either ascending order or descending order.