how to use arrays?
i have to come up with a program that adds up two binary strings.
example:
1001
+ 0001
---------
1010
i dont know how to use array for the carry bit. please help.
i dont know what code to put.
C programming!?
The resulting array can be up to 1 character longer. Just make the result at least 1 character larger than the largest of the 2 numbers being added.
for example
11111111
+11111111
----------------
111111110
Reply:The solution works like the grade-school algorithm for adding multiple digit numbers. (considering each digit as a position in the array).
In this case, instead of adding in base-2 you're making up some other base.
For this example suppose you use base-16 for each block (position in the array). actually any power of two will work provided you want to display the result as a binary string as well. (aside if doing this for decimal notiation you would use some power of 10).
Here is how it works.
#define MASK = 0xFF /* 1111 1111 binary */
int* doAdd(size_t resultlen, int[] lhs, size_t lhslen, int[] rhs, size_t rhslen){
int* ret = (int*)calloc(MAX(lhslen, rhslen) +1, sizeof(int));
int temp;
if (lhslen %26lt; rhslen){ swap(lhs,rhs); swap(lhslen,rhslen);}
for (int i =0; i %26lt; rhslen; ++i){
temp= lhs[i] + rhs[i];
ret[i] = temp % MASK;
ret[i] = temp / MASK;
}
return ret;
}
Note if the input is in the form of character data, the conversion from that into a number is pretty straight forward.
int* convert(char* str, size_t len){
int* ret = (int*)calloc(len/MASK, sizeof(int));
int magnitude = 0;
int pos = 0;
while( pos %26lt; len / MASK){
ret[ pos/MASK ] += atoi(str[pos])*magnitude;
magnitude = (++magnitude)%MASK;
pos++;
}
return ret;
}
Reply:Since I don't want to do your homework for you I will explain how arrays work.
Arrays are literally pointers to a segment of memory. You can have arrays point to a type of memory. These can be integers, booleans, characters, etc..
For example if I wanted to create an array that can contain 5 characters I could do it like so:
char arrMyArray[5];
I can then access each element in the array like so
arrMyArray[0] = 'H'
arrMyArray[1] = 'e'
arrMyArray[2] = 'l'
arrMyArray[3] = 'l'
arrMyArray[4] = 'o'
A simple way to think of them is to visualize an array like a number of crates sitting next to each other on the floor in a straight line. Each crate can only hold one item of the defined type. and you can access these elements based on their location (starting with zero)
So as a hint you may want to start with an array that can hold either integers (int) or booleans (bool)
like:
bool bits[8]
Good luck
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment