So this is my first post. I looked everywhere and can't find any help. Here is the problem: Create a 2 dimensional array of integers with 3 rows and 8 columns. Fill this array with 0’s and 1’s (binary numbers) randomly. Each row represents a byte. You are to add these three bytes up in binary. To store your answer, use a single dimensional array of 10 elements (to account for any carry overs). The array binums[3][8] has random 0 and 1’s in it. The array ans[10] has all 0’s in it. Start a variable “carry” with 0, and “total” with 0. Loop through each column, starting with the LAST column and add the carry amount to the total of the column (loop through all three values in the column, adding to total, then add carry). Then, set the LAST element of ans to total % 2, and set carry to total /2 (we are doing integer division). Repeat for each column, going right to left. Set total to 0 before each time.
And this is what I have so far. I'm stuck where I have to try to add the binary numbers from right to left. I've added them normal and cout them so I can get started but now I need to figure out how to add them from right to left. Please help:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
// Declare constants
const int DIM1 = 3; // number of rows
const int DIM2 = 8; // number of colums
// Function Prototypes
void fill_Ar(int arr[][DIM2]);
void print_Ar(int arr[][DIM2]);
void add(int binums[][DIM2], int ans[]);
void print_ans(int ans[]);
int main()
{
srand(time(0));
int binums[DIM1][DIM2], ans[DIM2 + (DIM1-1)];
fill_Ar(binums);
print_Ar(binums);
add(binums, ans);
//print_ans(ans); Commented this so i can test my code thus far
cout << endl;
return 0;
}
// function definitions below here
void fill_Ar(int arr[][DIM2])
{
int i,j, num = 0;
for (i = 0; i < DIM1; i++)
for (j = 0; j < DIM2; j++)
arr[i][j] = rand() % 2;
}
void print_Ar(int arr[][DIM2])
{
int i,j;
for (i = 0; i < DIM1; i++)
{
for (j = 0; j < DIM2; j++)
cout << arr[i][j] << " ";
cout << endl;
}
}
void add(int binums[][DIM2], int ans[]) //THIS IS WHERE I AM STUCK
{
int total, carry = 0, i, j;
for (j = 0; j < DIM2; j++)
{
total = 0;
for (i = 0; i < DIM1; i++)
{
total = total + binums[i][j];
}
cout << total << endl;
}
}
/***** Commented this so i can test my code thus far
void print_ans(int ans[])
{
}
****/