Sunday, 15 September 2013

Working on a code with for-loops and arrays

Working on a code with for-loops and arrays

In the program that I'm writing, I currently have a for-loop that goes
through an array, num[5], and checks to see if there are any 1s in that
array, which looks like:
int counter = 0;
for (int i = 1; i<=5; i++) {
if (num[i] == 1) {
counter++;
This works successfully, but I'm now trying to go through the array and
see what the indices of the 1s in the program are. So, if I have 01001, I
want to make an array that holds the positions of the 1s. The following is
what I've tried so far:
int b[counter];
for (int k = 0; k<= counter; k++) {
for (i = 0; i<=5; i++) {
if (num[i]==1) {
b[k] = i;
}
}
}
but this doesn't produce the desired result. When I type the string in,
say 1001, I get 444. Can someone tell me what I'm doing incorrectly?

No comments:

Post a Comment