#include<iostream>
int main
{
int x=40, y=2;
std::cout<<"The sum of "<<x<<" and "<<y<<" is "<<x+y<<std::endl;
}
Chat with our AI personalities
The following example shows one possible solution that emulates the half-adder and full-adder logic gates utilised by the CPU's arithmetic circuitry. There are more efficient ways to manipulate the individual bits to form the total, but the code is deliberately simplified for clarity whilst avoiding all usage of any arithmetic operators (only bitwise operators are used throughout). Note that even the while loop in main uses the sum() function rather than using the prefix increment operator (++) to increment the counter.
Code
#include
#include
int half_adder(int a, int b, int& c)
{
c=a&b; // return the carry bit (AND)
return(a^b); // return the sum bit (XOR)
}
int full_adder(int a, int b, int& c)
{
// The full-adder combines two half-adders such that the
// sum of the first becomes a in the second, while the
// given carry bit becomes b in the second. d and e are
// the carry bits returned from each half-adder
int d=0, e=0;
int s = half_adder( half_adder( a, b, d ), c, e );
c = d|e; // return the carry bit (OR)
return( s ); // return the sum bit
}
int sum(int lhs, int rhs)
{
// some variables...
int total=0, carry=0, pos=1;
int lbit, rbit, sum, tmp;
// repeat while there are bits to process, including
// the carry bit from the previous iteration (OR)
while(lhs|rhs|carry)
{
// mask the least-significant bits from both operands (AND)
lbit=lhs&1;
rbit=rhs&1;
// determine the sum of the two bits and the previous carry bit
sum = full_adder(lbit,rbit,carry);
// determine the correct position of the sum bit using bitshifts
tmp=pos;
while(tmp>>=1)
sum<<=1;
// update the total (OR)
total|=sum;
// bit shift the operands for next iteration
lhs>>=1;
rhs>>=1;
// bit shift the position for next iteration
pos<<=1;
}
return(total);
}
int main()
{
srand((unsigned)time(NULL));
int x,y;
int counter=0;
do
{
x=rand();
y=rand();
int z=sum(x,y);
std::cout< }while((counter=sum(counter,1))<10); } Example output 3583+13622=17205 9318+2059=11377 27249+30832=58081 22356+26289=48645 8301+14324=22625 28315+12451=40766 24452+16165=40617 14819+8566=23385 13642+25686=39328 30981+28975=59956
There is no algorithm. To add two numbers just put a + between them.
int a = 1 + 2;
Let c = a+b
It has nothing to do with C, it simply means: add 1 to a variable.
#include<iostream.h> #include<conio.h> void main() { int a, b, c; clrscr(); cout<<"enter the two numbers"; cin>>a; cin>b; c=a+b; cout<<"Addition of two numbers="<<c; getch(); }
Object oriented programming and structured programming.
#include<stdio.h> int add(int pk,int pm); main() { int k ,i,m; m=2; k=3; i=add(k,m); printf("The value of addition is %d\n",i); getch(); } int add(int pk,int pm) { if(pm==0) return(pk); else return(1+add(pk,pm-1)); } </stdio.h>