Sunday 6 July 2014

C++ program to subtract two numbers

Here are the C++ programs to subtract two numbers .Here I have given different methods like subtract two numbers using subtraction operator, without using subtraction operator, using function, using recursion and using bitwise operator etc.

C++ programs to subtract two numbers using subtraction operator

#include<iostream>
using namespace std;
int main()
{
    int a,b,c;
    cout<<"Enter Subtrahend and Minuend : ";
    cin>>a>>b;
    c=a-b;
    cout<<"Difference = "<<c<<endl;
    return 0;
}



C++ programs to subtract two numbers without using third variable

#include<iostream>
using namespace std;
int main()
{
    int a,b,c;
    cout<<"Enter Subtrahend and Minuend : ";
    cin>>a>>b;
    a=a-b;
    cout<<"Difference = "<<a<<endl;
    return 0;
}



C++ programs to subtract two numbers using functions

#include<iostream>
using namespace std;
int dif(int a,int b)
{
    return a-b;
}
int main()
{
    int a,b,c;
    cout<<"Enter two numbers : ";
    cin>>a>>b;
    c=dif(a,b);
    cout<<"Sum = "<<c<<endl;
    return 0;
}




C++ programs to subtract two numbers using pointers

#include<iostream>
using namespace std;
int main()
{
    int a,b,c;
    int *p,*q;
    p=&a;
    q=&b;
    cout<<"Enter two numbers : ";
    cin>>a>>b;
    c=*p-*q;
    cout<<"Sum = "<<c<<endl;
    return 0;
}



C++ programs to subtract two numbers using bitwise operator

#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
int main()
{
    int a,b,xo;
    cout<<"Enter Subtrahend and Minuend : ";
    cin>>a>>b;
    b=~b+1;
    while(b)
    {
        xo=a^b;
        b=a&b;
        b<<=1;
        a=xo;
    }
    cout<<"Difference = "<<a<<endl;
    return 0;
}




C++ programs to subtract two numbers without using subtraction operator

#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
int main()
{
    int a,b,c;
    cout<<"Enter Subtrahend and Minuend : ";
    cin>>a>>b;
    c=a+~b+1;
    cout<<"Difference = "<<c<<endl;
    return 0;
}




C++ programs to subtract two numbers using recursion

#include<iostream>
using namespace std;
int dif(int a,int b)
{
    if(b==0)
    return a;
    dif(a-1,b-1);
}
int main()
{
    int a,b,c;
    cout<<"Enter Subtrahend and Minuend : ";
    cin>>a>>b;
    c=dif(a,b);
    cout<<"Difference = "<<c<<endl;
    return 0;
}



1 comment: