You need to remember the difference between the
value zero and the human-readable
character zero.
Also, you don't need
two arrays. You only need one.
Take a moment to consider binary addition.
000 + 1 --> 001
The last zero turned into a one. Now:
001 + 1 --> 010
The last digit was already a one, so it was turned back into a zero and we added one to the remaining (leftmost two) digits.
Let's formulate that into some simple rules:
1. Adding '0' and '1' produces '1'.
2. Adding '1' and '1' produces '0', plus we need to apply the rules to the digits to the left of the one just changed.
Here we go. Given:
000
+ 1
Apply rule 1: (zero and one makes one)
= 001
Next:
001
+ 1
Apply rule 2: (first, turn that one into zero)
--> 000
(second, apply the rules to what remains)
000
+ 1
Apply rule 1: (zero and one makes one)
= 010
And again:
010
+ 1
Apply rule 1:
= 011
And one more time:
011
+ 1
Apply rule 2: (first, turn the one into a zero)
--> 010
(second, apply the rules to what remains on the left)
010
+ 1
Apply rule 2: (first, turn the one into a zero)
--> 000
(second, apply the rules to what remains on the left)
000
+ 1
Apply rule 1: (turn the zero into a one)
= 100
I suggest you write a little function that does this for you. It might have a prototype like:
void add_one_at( char* s, int index );
This function needs to apply both Rule 1 and Rule 2. Remember, Rule 2 involves calling the function again. That is, the function may need to call itself to apply the rules again. Don't forget to check that you don't call the function with an index less than zero. (The index is where you are adding one.)
Then, all you need is your initial array, and to use the function on it 2
3-1 times:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
int main()
{
char binary_digits[] = "000";
cout << binary_digits << endl;
for (int n = 0; n < 7; n++)
{
add_one_at( binary_digits, 2 ); // 2 is the index of the one's position
cout << binary_digits << endl;
}
return 0;
}
|
Hope this helps.