Monday 7 July 2014

C++ program to divide two numbers

Here are the C++ programs to divide two numbers .Here I have given different methods like divide two numbers using division operator, without using division operator, using function, using recursion and using bitwise operator etc. These are discussed below.



C++ program to divide two numbers using division operator

#include<iostream>
using namespace std;
int main()
{
    int a,b;
    float c;
    cout<<"Enter Dividend and Divisor : ";
    cin>>a>>b;
    c=a/(1.0*b);
    cout<<"Answer = "<<c;
    return 0;
}



C++ program to divide two numbers without third variable

#include<iostream>
using namespace std;
int main()
{
    float a,b;
    cout<<"Enter Dividend and Divisor : ";
    cin>>a>>b;
    a=a/b;
    cout<<"Answer = "<<a;
    return 0;
}


C++ program to divide two numbers using function

#include<iostream>
using namespace std;
float div(float a,float b)
{
    return a/b;
}
int main()
{
    float a,b,c;
    cout<<"Enter Dividend and Divisor : ";
    cin>>a>>b;
    c=div(a,b);
    cout<<"Answer = "<<c;
    return 0;
}



C++ program to divide two numbers using pointers

#include<iostream>
using namespace std;
int main()
{
    float a,b,*p,*q,c;
    p=&a;
    q=&b;
    cout<<"Enter Dividend and Divisor : ";
    cin>>a>>b;
    c=*p/(*q);
    cout<<"Answer = "<<c;
    return 0;
}



C++ program to divide two numbers using bitwise operator

#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
int main()
{
    int a,temp,b,xo,comb,sub=0,que,rem;
    cout<<"Enter Dividend ";
    cin>>a;
    cout<<"Enter Divisor ";
    cin>>b;
    sub=a;
    comb=~b+1;
    for(que=0;sub>=b;que++)
    {
       temp=comb;
       while(temp)
       {
           xo=sub^temp;
           temp=sub&temp;
           temp<<=1;
           sub=xo;
       }
    }
    cout<<"Quotient = "<<que<<endl<<"Remainder = "<<sub;
}



C++ program to divide two numbers without using division operator

#include<iostream>
using namespace std;
int main()
{
    int a,b,c=0;
    cout<<"Enter Dividend and Divisor : ";
    cin>>a>>b;
    while(a>=b)
    {
        a-=b;
        c++;
    }
    cout<<"Quotient = "<<c<<endl;
    cout<<"Remainder = "<<a<<endl;
    return 0;
}



C++ program to divide two numbers using recursion

#include<iostream>
using namespace std;
int divi(int n1,int n2,int &que)
{
    if(n2>n1)
        return n1;
    divi(n1-n2,n2,++que);
}
int main()
{
    int n1,n2,que=0;
    cout<<"Enter dividend and divisor : ";
    cin>>n1>>n2;
    cout<<"Remainder : "<<divi(n1,n2,que);
    cout<<endl<<"Quotient : "<<que;
    return 0;
}





No comments:

Post a Comment