Here are the C++ programs to add two numbers .There are many different methods two add two numbers like add two numbers without using '+' operator or through recursion etc. Some of them are discussed below
Method 1 : C++ program to two add two numbers
#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter two numbers : ";
cin>>a>>b;
c=a+b;
cout<<"Sum = "<<c<<endl;
return 0;
}
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter two numbers : ";
cin>>a>>b;
c=a+b;
cout<<"Sum = "<<c<<endl;
return 0;
}
Method 2 : C++ program to two add two numbers without using third variable
#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter two numbers : ";
cin>>a>>b;
a=a+b;
cout<<"Sum = "<<a<<endl;
return 0;
}
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter two numbers : ";
cin>>a>>b;
a=a+b;
cout<<"Sum = "<<a<<endl;
return 0;
}
Method 3 : C++ program to two add two numbers using function
#include<iostream>
using namespace std;
int sum(int a,int b)
{
return a+b;
}
int main()
{
int a,b,c;
cout<<"Enter two numbers : ";
cin>>a>>b;
c=sum(a,b);
cout<<"Sum = "<<c<<endl;
return 0;
}
using namespace std;
int sum(int a,int b)
{
return a+b;
}
int main()
{
int a,b,c;
cout<<"Enter two numbers : ";
cin>>a>>b;
c=sum(a,b);
cout<<"Sum = "<<c<<endl;
return 0;
}
Method 4 : C++ program to two add 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;
}
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;
}
Method 5 : C++ program to two add two numbers using bitwise operators
#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
int main()
{
int a,b,xo;
cout<<"Enter the first number ";
cin>>a;
cout<<"Enter second number ";
cin>>b;
while(b)
{
xo=a^b;
b=a&b;
b<<=1;
a=xo;
}
cout<<"Sum = "<<a;
return 0;
}
#include<stdio.h>
#include<math.h>
using namespace std;
int main()
{
int a,b,xo;
cout<<"Enter the first number ";
cin>>a;
cout<<"Enter second number ";
cin>>b;
while(b)
{
xo=a^b;
b=a&b;
b<<=1;
a=xo;
}
cout<<"Sum = "<<a;
return 0;
}
Method 6 : C++ program to two add two numbers using recursion
#include<iostream>
using namespace std;
int sum(int a,int b)
{
if(b==0)
return a;
sum(a+1,b-1);
}
int main()
{
int a,b,c;
cout<<"Enter two numbers : ";
cin>>a>>b;
c=sum(a,b);
cout<<"Sum = "<<c<<endl;
return 0;
}
using namespace std;
int sum(int a,int b)
{
if(b==0)
return a;
sum(a+1,b-1);
}
int main()
{
int a,b,c;
cout<<"Enter two numbers : ";
cin>>a>>b;
c=sum(a,b);
cout<<"Sum = "<<c<<endl;
return 0;
}
No comments:
Post a Comment