C++ program Booths Algorithm 2s Complement using array - c++

I have included the program in which I am having a logical problem. The program is based on booth's algorithm and I have put a snippet of it. In this 'working' snippet decimal number is accepted from the user converted to decimal form with the help of array (a[0]=1 LSB) and lastly the 2s complement is calculated of array b[].
Now, when I run the program:
#include<iostream>
using namespace std;
class booth
{
public:
int n;
int b[3];
int comb[3], q[3]; //b=multiplicand q=multiplier
int bb, qq; //bb and qq store actual decimal no.s
booth()
{
for(int i=0; i<4; i++)
{
b[i]=0; //b array stores multiplicand in binary
q[i]=0; //q array stores multiplier in binary
comb[i]=0; //will store calculated 2s complement in
binary
}
n=4;
bb=0;
qq=0;
}
void acceptMm();
void display();
};
void booth :: acceptMm() //function to accept value from user and
//converting it into binary in the form of
//array and then calculating its 2s complement
{
cout<<"Enter Multiplicand: ";
cin>>bb;
cout<<"Enter Multiplier: ";
cin>>qq;
//decimal to binary
int rem1, rem2, i=0, j=0; //rem1 and rem2 are remainders
while(qq!=0)
{
rem2=qq%2;
qq/=2;
q[i]=rem2;
i++;
}
cout<<q[3]<<q[2]<<q[1]<<q[0]<<endl; // to display binary no.
//again decimal to binary
while(bb!=0)
{
rem1=bb%2;
bb/=2;
b[j]=rem1;
j++;
}
cout<<b[3]<<b[2]<<b[1]<<b[0]<<endl; //to display binary no.
// 2s complement:
int ii=0;
int jj=4; //4 bit binary number
while(b[ii]==0 && jj!=0)
{
comb[ii]=b[ii];
ii++;
jj--;
}
comb[ii]=b[ii];
cout<<b[3]<<b[2]<<b[1]<<b[0]<<endl; //displayed value (problem)
ii++;
jj--;
if(jj==0)
{
return;
}
while(jj!=0)
{
if(b[ii]==0)
{
comb[ii]=1;
ii++;
jj--; }
else
{
comb[ii]=0;
ii++;
jj--;
}
}
}
void booth :: display()
{
cout<<"multiplicand\n";
for(int x=3; x>=0; x--)
{
cout<<b[x]<<" ";
}
cout<<endl;
cout<<"multiplier\n";
for(int j=3; j>(-1); j--)
{
cout<<q[j]<<" ";
}
cout<<endl;
cout<<"compliment of multiplicand\n";
for(int y=3; y>(-1); y--)
{
cout<<comb[y]<<" ";
}
}
int main()
{
booth obj;
cout<<"Booths Algorithm\n";
obj.acceptMm();
obj.display();
return 0;
}
Output
Booths Algorithm
Enter Multiplicand: 5
Enter Multiplier: 4
0100
0101
1101
multiplicand
1 1 0 1
multiplier
0 1 0 0
compliment of multiplicand
0 0 1 1
Here in the output I expect the 6th line as 0101 but get 1101. Why are the values of array b[] changing? The value of array b[] at line 5 is correct so why does it change? According to the code the value shouldnt be changing right?
I am stuck.. Please help!! Any suggestion will be appreciated!!

b, q and comb are array of 3 elements so b[3] is an array overflow (whose value is unknown). In fact comb being allocated right after b it is likely that b[3] equals comb[0].

You are doing an overflow . Do it like this. Simple .
class booth {
public:
int n;
int b[4];
int comb[4], q[4]; //b=multiplicand q=multiplier
int bb, qq; //bb and qq store actual decimal no.s
booth() {
for (int i = 0; i < 4; i++) {
b[i] = 0; //b array stores multiplicand in binary
q[i] = 0; //q array stores multiplier in binary
comb[i] = 0; //will store calculated 2s complement in }
n = 4;
bb = 0;
qq = 0;
}
}

Related

Number compliment of base 10 integer in c++

We have given a number and we have to flip its 0's and 1's in its binary form and after flipping it we have to written resultant decimal number of that flipped binary number .
For Example - Input: n = 5
Output: 2
Reason- 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
My try -
#include <iostream>
#include<math.h>
using namespace std;
int main(){
int n;
cin>>n;
int ans=0;
int a2ns=0;
int finalans=0;
int k=0;
int i=0;
int j=0;
while(n!=0){
int bit = n&1;
ans = bit*pow(10,i)+ans;
i++;
n=n>>1;
}
cout<<ans<<endl;
while(ans!=0){
int digit = ans&1;
if(digit==0){
digit =1;
}
else{
digit =0;
}
a2ns = digit*pow(10,i)+a2ns;
j++;
ans = ans>>1;
}
cout<<a2ns<<endl;
while(a2ns!=0){
int digit1 = a2ns%10;
if(digit1==1){
finalans = finalans + pow(2,k);
}
a2ns=a2ns/10;
k++;
}
cout<<finalans;
}
My Output-
235
11101011
1199999995
768
Expected Output-
235
11101011
00010100
20
My in my case error is coming while flipping the binary number from 1 to 0 and 0 to 1 , this part of my answer is having error while rest is correct . So please anyone can correct me where am i wrong in this code.
You can write simply this, assuming that T is an unsigned type
template< typename T >
T flip( T number ) {
#ifdef __cpp_lib_int_pow2
int numbits = std::bit_width<T>(number);
#else
int numbits = 0;
T tmp = number;
while ( tmp != 0 ) { tmp/=2; numbits++; }
#endif
T mask = ~(T(-1) << numbits);
number = ~number & mask;
return number;
}
std::bit_width<T>() is a C++20 feature so the macro __cpp_lib_int_pow2 tests for its existence.
Running a test
void test() {
for ( T j=0; j<10; ++j ) {
std::cout << "value:" << j << " bin:" << binary(j)
<< " flip:" << binary(flip(j)) << std::endl;
}
}
int main() {
test<uint32_t>();
}
Produces
value:0 bin:0 flip:0
value:1 bin:1 flip:0
value:2 bin:10 flip:1
value:3 bin:11 flip:0
value:4 bin:100 flip:11
value:5 bin:101 flip:10
value:6 bin:110 flip:1
value:7 bin:111 flip:0
value:8 bin:1000 flip:111
value:9 bin:1001 flip:110
Godbolt: https://godbolt.org/z/Pxjn3cr6o

Symmetric Matrix in C++

Checking whether a 2D Matrix is symmetric or not
Task is to output YES if the matrix is symmetric else output NO.
I am not getting the expected result. Can someone please help me out and please let me know what's wrong with this code
#include<iostream>
#include<vector>
using namespace std;
bool rev(int n)
{
int n1,d,rn=0;
n1=n;
while(n>0)
{
d=n%10;
rn=(rn*10)+d;
n/=10;
}
if(n1==rn)
{return true;}
else
return false;
}
bool XAxisSymCheck(vector<int> vect)
{
// Declaring iterator to a vector
vector<int>::iterator ptr;
for (ptr = vect.begin(); ptr < vect.end(); ptr++)
{ if(!rev(*ptr)) // reversing the elements in each element of vector to check whether its symmetric or not .. similar to palindrome
{
return false;
}
}
}
int main()
{int testcase;
cin>>testcase;
for(int k=0;k<testcase;++k)
{vector<int> rows;
bool IsSymmetric=true;
int row;
cin >> row;
// read each row and append to the "rows" vector
for (int r = 0; r < row; r++)
{
int line;
cin >> line;
rows.push_back(line);
}
if(XAxisSymCheck(rows))
{int i,j;
i=0;
j=row-1;
while(i<j) // looping through the elements of vector and checking the first element with last element , second element with the second last element and so on.
{
if(rows[i]!=rows[j])
{
IsSymmetric=false;
break;
}
i++;
j--;
}
}
else
{
IsSymmetric=false;
}
cout << (IsSymmetric ? "Yes" : "No") << endl;
}
return 0;
}
Input:
First line contains T - number of test cases.
T test cases follow.
First line of each test case contains the N - size of matrix.
Next N lines contains binary strings of length N.
Output:
Print YES or NO in a new line for each test case
SAMPLE INPUT
5
2
11
11
4
0101
0110
0110
0101
4
1001
0000
0000
1001
5
01110
01010
10001
01010
01110
5
00100
01010
10001
01010
01110
SAMPLE OUTPUT
YES
NO
YES
YES
NO
Test Case #1: Symmetric about both axes, so YES.
Test Case #2: Symmetric about X-axis but not symmetric about Y-axis, so NO.
Test Case #3: Symmetric about both axes, so YES.
Test Case #4 and #5 are explained in statement.
There are three problems with your code
1) You are never returning true from XAxisSymCheck (this can easily discovered by inspecting the compiler warnings, eg g++ -Wall matrix.cpp)
bool XAxisSymCheck(vector<int> vect) {
vector<int>::iterator ptr;
for (ptr = vect.begin(); ptr < vect.end(); ptr++) {
if(!rev(*ptr, vect.size()))
return false;
}
return true;
}
2) When your XAxisSymCheck fails, you are not setting IsSymmetric to false (at least in the original post before the edit)
for(int k=0;k<testcase;++k) {
vector<int> rows;
bool IsSymmetric = true;
// ....
if (XAsxisSymCheck(rows)) {
// ...
} else {
IsSymmetric = false;
}
cout << (IsSymmetric ? "Yes" : "No") << endl;
}
3) Your reverse check fails, if a line has leading zeros, because the reverse is not multiplicated by 10 often enough.
bool rev(int n,int len) {
int n1,d,rn=0;
n1=n;
for (int i = 0; i < len; i++)
{
d=n%10;
rn=(rn*10)+d;
n/=10;
}
return n1==rn;
}

How to grab first digit of an int in an int array?

I have an int array called doubledNumbers and if a number in this array is greater than 9, I want to add the digits together. (example, 16 would become 1+6=7, 12 would become 3, 14 would become 5, etc)
Lets say I had the following numbers in doubledNumbers:
12 14 16 17
I want to change the doubledNumbers to:
3 5 7 8
I'm unsure how to do this for an int array as I get the error
invalid types 'int[int]' for array subscript
This is the code I have (thrown in a for loop):
if (doubledNumbers[i]>9) {
doubledNumbers[i]=doubledNumbers[i][0]+doubledNumbers[i][1];
There is nothing like decimal digits in an int. There are (mostly 32 or 64) binary digits (bits) and the base of 2 is not commensurable with the base of 10. You’ll need to divide your numbers by 10 to get decimal digits.
unsigned int DigitSum(unsigned int input, unsigned int base = 10)
{
unsigned int sum = 0;
while(input >= base)
{
sum += input % base;
input /= base;
}
sum += input;
return sum;
}
I used unsigned int. The example cannot be directly used for negative numbers but the modification is not difficult.
You can use something like this
#include <iostream>
using namespace std;
int sumofdigits(int);
int main()
{
// your code goes here
int a[5] ={12,14,15,16,17};
for(int i=0;i<5;i++)
{
int m=sumofdigits(a[i]);
cout <<m<<" ";
}
return 0;
}
int sumofdigits(int n)
{
int sum=0;
while(n!=0)
{
int d=n%10;
sum=sum+d;
n=n/10;
}
return sum;
}
// % operator is used for calculating remainder.
You can do like this,
#include<iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int a[5]={1,2,5,11,12};
int length = sizeof(a)/sizeof(int);
for(int i=0;i<length;i++)
{
if ( a[i] >9 )
{
stringstream ss;
ss << a[i];
string a1 = ss.str();
const char * s = a1.c_str();
int sum=0;
while (*s !='\0')
{
cout<<*s<<endl;
sum += (*s - '0');
s++;
}
cout<<"num:"<< sum <<"\n";
}
}
}
int A[2];
A[0] = 2;
A[1] = 10;
for (int i=0;i<2;i++) {
if (a[i] > 9) {
int b = a[i]%10;
int c = a[i]/10;
int d = b+c;
cout << d;
}
}
It's only for two digit numbers(10 -99) and for more than that (after 99) we will have to change logic.

create an array such that it contains elements from 0 to N in binary

I need a fast algorithm which will generate all possible numbers upto a given number N in binary into an array.
e.g N=3
Then the array should be {0,0,0},{0,0,1}.....{1,1,1}
N<=17.
I have tried this so far which is a recursive solution.
void print_digits(int n, std::string const& prefix = "") {
if (!n) {
printf("%s,",prefix.c_str());
return;
}
print_digits(n-1, prefix + '0');
print_digits(n-1, prefix + '1');
}
i need a better algorithm.
All the integers in C++ are stored directly in memory as their binary representation. Thus, if you just want to store N numbers, you should just write them directly into an array "as-is"
std::vector<unsigned> Numbers;
// if N is length of the number, calculate the maximum as 2^N - 1
long long Max = 1 << N - 1;
for (unsinged i = 0; i < Max; ++i)
Numbers.push_back(i);
If you want to write them in the binary representation, it's also pretty straightforward, even if you want to code it all by yourself. (Please excuse me, as this is just an simple example implementation)
void PrintAsBits(unsigned value) {
for (int i = sizeof(unsigned) * 8 - 1; i >= 0; --i)
cout << ((1 << i) & value) ? 1 : 0;
cout << '\n';
}
Just in case anyone cares anymore, the following code implements the original spec, which calls for a way to populate a 2-dimensional array where each value is represented as a numeric array whose elements correspond to its value's binary digits, in big-endian order.
#include <iostream>
static const int DIGIT_COUNT = 10;
static const int VALUE_COUNT = 1 << DIGIT_COUNT;
unsigned char g_binarray[VALUE_COUNT][DIGIT_COUNT];
void Populate() {
for(int i=0; i<VALUE_COUNT; ++i) {
unsigned char (&curr)[DIGIT_COUNT] = g_binarray[i];
for(int di=0; di<DIGIT_COUNT; ++di) {
curr[di] = unsigned char((i >> (DIGIT_COUNT - 1 - di)) & 1);
}
}
}
void DumpArray() {
static const char *digits = "01";
for(int i=1; i<VALUE_COUNT; ++i) {
for(int di=0; di<DIGIT_COUNT; ++di) {
std::cout << digits[!!g_binarray[i][di]];
}
std::cout << " " << i << std::endl;
}
}
int main(int argc, char* argv[]) {
Populate();
DumpArray();
return 0;
}
As I wrote in 1 post:
Example: If you need of length 4, then you must have 2^4 = 16 different arrays.
You can use this simple Java code to generate all arrays:
for (int i=0; i < 16; i++) {
System.out.println(Integer.toBinaryString(i));
}
The output of this:
0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111

how to set in a binary form of number at some position 1 or 0

Suppose I have an eight bit number, I want to set at each bit position number 1 or zero, it is dynamic situation.
Suppose for example such situation, user enters two numbers which are equal or differs only by one, and I want that at each iteration from 0 position to seven, write these 0 and 1 in binary form of number, how can I implement it in cycle? Please help me.
An example:
int result = 0;
for (int i = 0; i < 8; i++) {
int x, y;
cin >> x >> y;
if (x == y) {
// set at i position 0;
}
else if ((x-y) == 1) {
// set at i position 1;(in result number)
}
}
updated :
it is what i want to implement :
Adding two 8-bit two's complement binary numbers
here is code for this
#include <iostream>
using namespace std;
int main(){
int x,y;
cin>>x>>y;
int result=0;
int carry=0;
int sum=0;
for (int i=0;i<8;i++){
sum=carry;
sum+= (x&(1<<i));
sum+=(y&(1<<i));
if (sum>1){
sum-=2;
carry=1;
}
else{
carry=0;
}
result|=sum;
result<<=1;
}
cout<<result<<" "<<endl;
return 0;
}
You can change individual bits with AND and OR binary operators.
For example:
//set first bit to 1
value |= 1;
//set fourth bit to 0
value &= ~(1<<3);
//set 6th bit to 1
value |= (1<<5);
I don't know what happens if your inputs are different by two but you might want something like this:
int result = 0;
for (int i = 0; i < num_bits; ++i) {
int a, b;
std :: cin >> a >> b;
result |= (a != b);
result <<= 1;
}
Consider bit shifting.
To set the bit:
result |= (1<<i);
Un-setting the bit is left as an excercise to the reader.